从 Go 中的 REST API 端点返回 json 对象
php小编百草在这篇文章中将为大家介绍如何从Go语言编写的REST API端点返回json对象。作为一种常见的数据交换格式,json在web开发中被广泛使用。通过使用Go语言的net/http包和encoding/json包,我们可以轻松地将数据转换为json格式并返回给客户端。本文将详细说明这个过程,并提供示例代码来帮助读者理解和实践。无论您是初学者还是有经验的开发者,本文都将对您有所帮助。让我们开始吧!
问题内容
我正在使用 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) } }
以上是从 Go 中的 REST API 端点返回 json 对象的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Go语言中用于浮点数运算的库介绍在Go语言(也称为Golang)中,进行浮点数的加减乘除运算时,如何确保精度是�...

Go爬虫Colly中的Queue线程问题探讨在使用Go语言的Colly爬虫库时,开发者常常会遇到关于线程和请求队列的问题。�...

Go语言中哪些库是大公司开发或知名开源项目?在使用Go语言进行编程时,开发者常常会遇到一些常见的需求,�...

关于Goland中自定义结构体标签的问题在使用Goland进行Go语言开发时,经常会遇到一些配置上的问题。其中一个常�...

Go语言中实现高效键值对存储的正确方法在使用Go语言开发类似于Redis的键值对内存存储器时,如何实现最佳性能...

Go指针语法及viper库使用中的寻址问题在使用Go语言进行编程时,理解指针的语法和使用方法至关重要,尤其是在...

Go语言海量URL访问性能优化策略本文针对使用Go语言处理海量URL访问的问题,提出性能优化方案。现有程序从CSV�...
