Return json object from REST API endpoint in Go
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

Go pointer syntax and addressing problems in the use of viper library When programming in Go language, it is crucial to understand the syntax and usage of pointers, especially in...

Regarding the problem of custom structure tags in Goland When using Goland for Go language development, you often encounter some configuration problems. One of them is...

The correct way to implement efficient key-value pair storage in Go language How to achieve the best performance when developing key-value pair memory similar to Redis in Go language...

Performance optimization strategy for Go language massive URL access This article proposes a performance optimization solution for the problem of using Go language to process massive URL access. Existing programs from CSV...
