DEV Community

Sukma Rizki
Sukma Rizki

Posted on

Http Request Form Data at Golang

There are several things you need to remember to insert data into a request
import package bytes and net/url.

import "bytes"
import "net/url"

Enter fullscreen mode Exit fullscreen mode

Create a new function, the content is a request to http://localhost:8080/user with the data
inserted is ID .
func fetchUser(ID string) (student, error) {
var err error
var client = &http.Client{}
var data student
var param = url.Values{}
param.Set("id", ID)
var payload = bytes.NewBufferString(param.Encode())
request, err := http.NewRequest("POST", baseURL+"/user", payload)
if err != nil {
return data, err
}
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
response, err := client.Do(request)
if err != nil {
return data, err
}
defer response.Body.Close()
err = json.NewDecoder(response.Body).Decode(&data)
if err != nil {
return data, err
}
return data, nil
}

The contents of the function above can be seen to have some similarities with the function
fetchUsers() before.
The url.Values{} statement will produce an object that will later be used
as a data request form. On this object what data needs to be set
want to be sent using the Set() function as in param.Set("id", ID) .
The statement bytes.NewBufferString(param.Encode()) means, a form data object
encoded and then converted into bytes.Buffer form, which is later inserted
in the third parameter of the http.NewRequest() function call.
Because the data to be sent is encoded, the header needs to be set to a type
the content of the request. The code request.Header.Set("Content-Type", "application/x www-form-urlencoded") means that the request content type is set as application/x www-form-urlencoded .

The response from the /user endpoint is not a slice, but an object. Then on
When decoding, you need to ensure the type of variable that contains the decoded response data
is student (not []student ).
Continue to coding, finally, implement fetchUser() in the function
main() .
func main() {
var user1, err = fetchUser("E001")
if err != nil {
fmt.Println("Error!", err.Error())
returns
}
fmt.Printf("ID: %s\t Name: %s\t Grade: %d\n", user1.ID, user1.Name, user1.G
}

For testing purposes, we hardcode the ID value "E001" . Run the program
to test whether the data returned is appropriate.

Top comments (0)