The first thing is to import the net/http package, apart from containing tools for web creation purposes, it also contains functions for making http requests, one of the packages that is always used is http.NewRequest(). Let's put it into practice directly
import the required packages and prepare a template or what we usually call a student struct which will later be used as the response data type from the web API.
`package main
import "fmt"
import "net/http"
import "encoding/json"
//Testing localhost dengan port 8080
var baseURL = "http://localhost:8080"
//Struct untuk menampung data
type student struct {
ID string
Name string
Grade int
}
`
Then after that create a fetchuser() function, the function performs the task of requesting data, then displaying it.
func fetchUsers() ([]student, error) {
var err error
var client = &http.Client{}
var data []student
request, err := http.NewRequest("GET", baseURL+"/users", nil)
if err != nil {
return nil, err
}
response, err := client.Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
err = json.NewDecoder(response.Body).Decode(&data)
if err != nil {
return nil, err
}
return data,nil
}
The &http.Client{} statement produces an http.Client instance. This object
later required for request execution.
The http.NewRequest() function is used to create a new request. Function
It has 3 parameters that must be filled in.
- The first parameter contains the request type POST or GET or other
- The second parameter is the request destination URL
- Third parameter, data request form (if any) The function produces an instance of type http.Request . the object later inserted during request execution. The way to execute the request itself is by calling the Do() method http.Client instance that has been created, with parameters is instance the request. For example, client.Do(request) . The method returns an instance of type http.Response , which is in it contains information returned from the web API. Response data can be retrieved via the Body property in string form. Use JSON Decoder to convert it into JSON form. For example, you can seen in the code above, json.NewDecoder(response.Body).Decode(&data) . After that then we can display it. Please note, response data needs to be closed after it is not used. The method as in the defer response.Body.Close() code. Next, execute the fetchUsers() function in the main() function.
func main() {
var users, err = fetchUsers()
if err != nil {
fmt.Println("Error!", err.Error())
return
}
for _, each := range users {
fmt.Printf("ID: %s\t Name: %s\t Grade: %d\n", each.ID, each.Name, each
}
}
Ok, finally before starting testing, make sure you have run the application in the chapter
previously (A.54. Web Service API Server). Then start the cmd/terminal prompt
new and run the program we just created in this chapter.
Good luck and hopefully useful
Top comments (0)