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

Return json object from REST API endpoint in Go

WBOY
WBOYforward
2024-02-09 08:00:31621browse

从 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)

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"`
}

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)

}

This is what is printed. Print value without object key

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

should print

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

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)
    }
}

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)
    }
}

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete