Golang Advanced (v) JSON processing for--restful development

Source: Internet
Author: User
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)}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.