英文:
return json object from REST API endpoint in Go
问题
我正在使用golang构建API。我希望这个端点返回JSON数据,以便我可以在前端中使用它。
http.HandleFunc("/api/orders", createOrder)
目前我的函数没有返回JSON对象,并且jsonMap
变量没有将服务器的响应体映射到CreateOrder
结构体中。
我的结构体:
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'
},
...
]
}
英文:
I'm building the API with golang. I want this endpoint to return json data so I can use it in my frontend.
http.HandleFunc("/api/orders", createOrder)
Currently my function is not returning a json object and jsonMap variable is not maping the response body to of the server with the Create struc
My struct
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 gets printed. Prints the value without the keys of the object
{2MH36251C2958825N CREATED [{something self GET} {soemthing approve GET}]}
Should print
{
id: '8BW01204PU5017303',
status: 'CREATED',
links: [
{
href: 'url here',
rel: 'self',
method: 'GET'
},
...
]
}
答案1
得分: 1
func createOrder(w http.ResponseWriter, r *http.Request) {
// ...
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Println("发生错误:", err)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK /* 或者 http.StatusCreated(取决于你使用的API) */ {
log.Println("请求失败,状态为:", http.Status)
w.WriteHeader(resp.StatusCode)
return
}
// 解码来自外部服务的响应
v := new(CreateOrder)
if err := json.NewDecoder(resp.Body).Decode(v); err != nil {
log.Println(err)
return
}
// 发送响应到前端
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("发生错误:", err)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK /* 或者 http.StatusCreated(取决于你使用的API) */ {
log.Println("请求失败,状态为:", http.Status)
w.WriteHeader(resp.StatusCode)
return
}
// 将外部服务的响应复制到前端
w.WriteHeader(resp.StatusCode)
if _, err := io.Copy(w, resp.Body); 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
}
// 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 the data from the external service to the frontend unchanged, you should be able to do something like this:
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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论