首页 > Web开发 > 详细

[Go] golang http下返回json数据

时间:2020-05-18 20:05:55      阅读:58      评论:0      收藏:0      [点我收藏+]

需求返回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, Msg: "验证成功"})
            w.Write(msg)
        } else {
            w.WriteHeader(400)
            w.Write(msg)
        }
    } else {
        w.WriteHeader(400)
        w.Write(msg)
    }
}

技术分享图片

 

[Go] golang http下返回json数据

原文:https://www.cnblogs.com/taoshihan/p/12912599.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!