This is a creation in Article, where the information may have evolved or changed.
Objective
RESTful development, object to Json,json to the object is very frequent operation, how to less repetitive code, for this purpose to open this article
All your code on GitHub.
Simplifying data structures
Each time you need to return the data have code,msg,data these fields, each type of these fields is too complicated, there is interface way to replace any type, and then use when the data field and any other type of combination
package modeltypestruct { string `json:"code"` Msg string `json:"msg,omitempty"` interface`json:"data,omitempty"`}typestruct { string`json:"username"` string`json:"password,omitempty"`}
JSON and HTTP requests together
The JSON-processing wrapper for Golang, which allows the object to be read directly from the HTTP request, outputting the object in JSON format to the response
PackageToolsImport("bytes" "Encoding/json" "FMT" "Io/ioutil" "Net/http")//Marshaljson put objects in JSON format in responsefuncMarshaljson (w http. Responsewriter, VInterface{}) error {data, err: = json. Marshal (v)ifErr! =Nil{returnERR} FMT. Fprint (W,string(data))return Nil}//Unmarshaljson Remove object from RequestfuncUnmarshaljson (req *http. Request, VInterface{}) Error {result, err: = Ioutil. ReadAll (req. Body)ifErr! =Nil{returnERR} JSON. Unmarshal ([]byte(bytes. Newbuffer (Result). String ()), V)return Nil}
Call
After the above processing, the call becomes quite easy, does not need to do more repetition coding, the code readability greatly improves
func UserLoginndler(w http.ResponseWriter, r *http.Request) { user := &model.User{} tools.UnMarshalJson(r, user) "1001""账号或者密码错误"} if"sweetop""123456" { "0""success"} } tools.MarshalJson(w, resp)}
func UserListHandler(w http.ResponseWriter, r *http.Request) { "0""success"} make([]model.User, 0) append"sweetop"}) tools.MarshalJson(w, resp)}