DEV Community

Sukma Rizki
Sukma Rizki

Posted on • Edited 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
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (2)

Collapse
 
nigel447 profile image
nigel447

this is good work, however its hard to read, if u can u should format the code for readability using markdown code blocks (3 backticks,) u can get this from the editor toolbar(at the bottom) its the box containing < >, not the < >

with some formatting your code looks like this in a code block

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
    }
      ............  // rest of the code
Enter fullscreen mode Exit fullscreen mode

in any golang code block we can use := rather than var where appropriate

your post text content can be made more readable by putting empty new lines between logical statements, that way the text layout expresses the logic, thanks for posting this

Collapse
 
sukmarizki04 profile image
Sukma Rizki

Thanks for sugestion