我正在使用 golang 构建 api。我希望此端点返回 json 数据,以便我可以在我的前端中使用它。
http.handlefunc("/api/orders", createorder)
目前我的函数没有返回 json 对象,并且 jsonmap 变量没有使用 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' }, ... ] }
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) } }