Making HTTP Requests with JSON Body in JavaScript and Golang



Currently, I am in the process of learning golang and attempting to “convert” a previous PHP script into golang. However, I have a query concerning the process of “decoding” the body of a POST request made by an http.Client. (Perhaps I am too advanced in age to acquire knowledge in a new programming language…)

Here is a condensed version of my code:

var my_client = &http.Client{
    Transport: my_Trans,        // Defined elsewhere
    Timeout:   my_TimeOut,      // Defined elsewhere
logininfo := map[string]interface{}{"username": user, "password": pw}
payload, _ := json.Marshal(logininfo)
request, _ := http.NewRequest("POST", "", bytes.NewBuffer(payload))
request.Header.Set("Content-Type", "application/json")
response, err := my_client.Do(request)
defer response.Body.Close()
log.Printf("%s", response.Body)

The resulting output is the response body, which is represented in the following manner:

2021/01/13 13:50:31 response.Body
2021/01/13 13:50:31 {{"data":{"state":1,"id":"1234567890","Token":"ABCDEF0123456","lastloginip":"","lastlogintime":1600000000},"error":{"code":0,"description":"0"}}

My intention is to retrieve the “id” and “Token” fields from that entity. The solution I have devised is as follows:

type my_loginResult struct {
    Data struct {
        State         int    `json:"state"`
        Id            string `json:"id"`
        Token         string `json:"Token"`
        Lastloginip   string `json:"lastloginip"`
        Lastlogintime int    `json:"lastlogintime"`
    Error struct {
        Code        int    `json:"code"`
        Description string `json:"description"`
resultjson := my_loginResult{}
tmp_body, _ := ioutil.ReadAll(response.Body)
json.Unmarshal(tmp_body, &resultjson)
id = resultjson.Data.Id
token = resultjson.Data.Token

Is this the optimal approach for decoding the body?

In PHP I can just do:

id = $response->body->data->id;
token = $response->body->data->Token;




I believe your solution will be effective. Are you encountering any problems? Additionally, you have the option to utilize a map instead of a struct, although this may introduce complications.

Frequently Asked Questions