API response
For API, json data is very simple to handle. Receive parameters and return as json, client side (web and mobile) can handle easily.
To get JSON response, we need to understand JSON handle in go.
In previous blog, I explained about JSON handle in go and simple way to handle json data in web.
These are entries.
JSON in go
To support JSON data, use “encoding/json” package.
This package has json Marshal, Unmarshal method
- Marshal : struct(data) -> json object
- UnMarshal : byte data -> struct (data)
In UnMarshal, to use string to byte, we can get struct data from string.
Return data of Marshal can use response data.
Example
params.go
package web import ( "encoding/json" "fmt" "net/http" ) // json response type DataJson struct { Name string Title []string } func jsonRes(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") data := &DataJson{ Name: "Hoo Foo", Title: []string{"1st", "3rd", "1st"}, } json, _ := json.Marshal(data) w.Write(json) }
The step
- Set header content-type application/json
- Create data (struct)
- Call Marshal for response
- Write data
コメント