[Go] golang http下返回json数据

前端之家收集整理的这篇文章主要介绍了[Go] golang http下返回json数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

需求返回json格式编码的结构体,需要返回content-type 

返回不同的响应码

 

结构体的定义,因为可导出的结构体,必须大写,如果要小写,就得加这个别名

type JsonResult  struct{
    Code int `json:"code"`
    Msg  string `json:msg`
}

从post中获取到字段后,返回对应的结果,设置header必须在返回响应码之前调用

//验证接口
func check(w http.ResponseWriter,r *http.Request) {
    email := r.PostFormValue(email)
    server := r.PostFormValue(server)
    password := r.PostFormValue(password)
    msg,_ := json.Marshal(tools.JsonResult{Code: 400,Msg: 验证失败})

    w.Header().Set(content-type",text/json)
    if email != "" && server != "" && password != "" {
        res := tools.CheckEmailPassword(server,email,password)
        if res {
            msg,_ = json.Marshal(tools.JsonResult{Code: 200,1)">验证成功})
            w.Write(msg)
        } else {
            w.WriteHeader(400)
            w.Write(msg)
        }
    }  {
        w.WriteHeader()
        w.Write(msg)
    }
}

 

猜你在找的Go相关文章