Home > Backend Development > Golang > Return json object from REST API endpoint in Go

Return json object from REST API endpoint in Go

WBOY
Release: 2024-02-09 08:00:31
forward
650 people have browsed it

从 Go 中的 REST API 端点返回 json 对象

In this article, php editor Baicao will introduce how to return json objects from the REST API endpoint written in Go language. As a common data exchange format, json is widely used in web development. By using the Go language's net/http package and encoding/json package, we can easily convert the data into json format and return it to the client. This article will explain this process in detail and provide sample code to help readers understand and practice. Whether you are a beginner or an experienced developer, this article will help you. let's start!

Question content

I am using golang to build api. I want this endpoint to return json data so I can use it in my frontend.

http.handlefunc("/api/orders", createorder)
Copy after login

Currently my function does not return a json object, and the jsonmap variable is not used create struc Map the response body to the server

My structure

type createorder struct {
    id     string  `json:"id"`
    status string  `json:"status"`
    links  []links `json:"links"`
}
Copy after login

My createorder function (updated based on comments)

func createorder(w http.responsewriter, r *http.request) {
    accesstoken := generateaccesstoken()
    w.header().set("access-control-allow-origin", "*")
    fmt.println(accesstoken)

    body := []byte(`{
        "intent":"capture",
        "purchase_units":[
           {
              "amount":{
                 "currency_code":"usd",
                 "value":"100.00"
              }
           }
        ]
     }`)

    req, err := http.newrequest("post", base+"/v2/checkout/orders", bytes.newbuffer(body))
    req.header.set("content-type", "application/json")
    req.header.set("authorization", "bearer "+accesstoken)

    client := &http.client{}
    resp, err := client.do(req)

    if err != nil {
        log.fatalf("an error occured %v", err)
    }

    fmt.println(resp.statuscode)
    defer resp.body.close()

    if err != nil {
        log.fatal(err)
    }

    var jsonmap createorder

    error := json.newdecoder(resp.body).decode(&jsonmap)

    if error != nil {
        log.fatal(err)
    }

    w.writeheader(resp.statuscode)
    json.newencoder(w).encode(jsonmap)

}
Copy after login

This is what is printed. Print value without object key

{2mh36251c2958825n created [{something self get} {soemthing approve get}]}
Copy after login

should print

{
  id: '8BW01204PU5017303',
  status: 'CREATED',
  links: [
    {
      href: 'url here',
      rel: 'self',
      method: 'GET'
    },
    ...
  ]
}
Copy after login

Solution

func createorder(w http.responsewriter, r *http.request) {
    // ...

    resp, err := http.defaultclient.do(req)
    if err != nil {
        log.println("an error occured:", err)
        return
    }
    defer resp.body.close()
    
    if resp.statuscode != http.statusok /* or http.statuscreated (depends on the api you're using) */ {
        log.println("request failed with status:", http.status)
        w.writeheader(resp.statuscode)
        return
    }

    // decode response from external service
    v := new(createorder)
    if err := json.newdecoder(resp.body).decode(v); err != nil {
        log.println(err)
        return
    }
    
    // send response to frontend
    w.writeheader(resp.statuscode)
    if err := json.newencoder(w).encode(v); err != nil {
        log.println(err)
    }
}
Copy after login

Alternatively, if you want to send data from an external service to the frontend immutably, you should be able to do the following:

func createOrder(w http.ResponseWriter, r *http.Request) {
    // ...

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Println("An Error Occured:", err)
        return
    }
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK /* or http.StatusCreated (depends on the API you're using) */ {
        log.Println("request failed with status:", http.Status)
        w.WriteHeader(resp.StatusCode)
        return
    }

    // copy response from external to frontend
    w.WriteHeader(resp.StatusCode)
    if _, err := io.Copy(w, resp.Body); err != nil {
        log.Println(err)
    }
}
Copy after login

The above is the detailed content of Return json object from REST API endpoint in Go. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template