在Go语言中从REST API端点返回json对象

xa9qqrwz  于 2022-12-15  发布在  Go
关注(0)|答案(1)|浏览(241)

我正在用golang构建API,我希望这个端点返回json数据,这样我就可以在我的前端使用它。

http.HandleFunc("/api/orders", createOrder)

目前,我的函数没有返回json对象,jsonMap变量也没有将响应主体Map到Create struc服务器
我的结构

type CreateOrder struct {
    Id     string  `json:"id"`
    Status string  `json:"status"`
    Links  []Links `json:"links"`
}

我的CreateOrder函数(根据评论更新)

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)

}

这就是打印的内容。打印不带对象键的值

{2MH36251C2958825N CREATED [{something self GET} {soemthing approve GET}]}

应打印

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

wvt8vs2t1#

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

或者,如果您希望将数据从外部服务发送到前端而不做任何更改,您应该能够执行类似以下的操作:

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

相关问题