需求返回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) } }