This tutorial help to consume third-party HTTP post API using Golang in json format. There are a lot of products and tools available that provide access to his functionality using Rest Api.
The Rest API could be GET/POST/PUT or Delete type, these are HTTP method to access rest API. We will use HTTP post type rest call to post some data into the server, The Post payloads and Response data format is in JSON.
We will use 'encode/json'
package to reading payload and send the response in JSON format.Let’s start Implementing of POST Http access using golang HTTP.
Step 1: We will create post routes into main.go
file.
routes.HandleFunc("/user", AddUser).Methods("POST")
Step 2: We will create interface struct for user.
type New_User struct { Name string `json:"name"` Job string `json:"job"` } type New_User_Resp struct { Name string `json:"name"` Job string `json:"job"` ID string `json:"id"` CreatedAt time.Time `json:"createdAt"` }
Step 3: We will add method into handler file.
func AddUser(w http.ResponseWriter, r *http.Request) { }
Step 4: We will add below code into AddUser()
method.
func AddUser(w http.ResponseWriter, r *http.Request) { var user New_User decoder := json.NewDecoder(r.Body) decoder.Decode(&user) jsonValue, _ := json.Marshal(user) fmt.Printf("%+v\n", user) u := bytes.NewReader(jsonValue) req, err := http.NewRequest("POST", "https://reqres.in/api/users", u) if err != nil { fmt.Println("Error is req: ", err) } req.Header.Set("Content-Type", "application/json") // create a Client client := &http.Client{} // Do sends an HTTP request and resp, err := client.Do(req) if err != nil { fmt.Println("error in send req: ", err.Error()) w.WriteHeader(400) //w.Write(err) } defer resp.Body.Close() w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK)\ var data New_User_Resp res, err := json.Unmarshal(resp.Body, &data) w.Write(data) }
The post How To Consume Post Rest API Using Golang with JSON appeared first on Rest Api Example.