package main import ( "encoding/json" "log" "net/http" ) func userLogin(writer http.ResponseWriter, request *http.Request) { //接收参数 request.ParseForm() mobile := request.PostForm.Get("mobile") passwd := request.PostForm.Get("passwd") loginok := false if(mobile=="123456" && passwd=="123456"){ loginok = true } if(loginok){ data := make(map[string]interface{}) data["id"]=1 data["token"]="test" returnMsg(writer,0,data,"") }else{ returnMsg(writer,-1,nil,"密码不正确") } //返回数据 //str := `{"code":0,"data":{"id":1,"token":"test"}}` //if(!loginok){ // str = `{"code":-1,"msg":"密码错误"}` //} 设置header 为json 默认的text/html 设置header //writer.Header().Set("Content-Type","application/json") 设置200状态 //writer.WriteHeader(http.StatusOK) 输出 //writer.Write([]byte(str)) } func main() { //更具路由执行方法 http.HandleFunc("/user/login",userLogin) //启动web服务器 http.ListenAndServe(":8989", nil) } type returnFormat struct { Code int Msg string Data interface{} } func returnMsg(w http.ResponseWriter,code int,data interface{},msg string) { w.Header().Set("Content-Type","application/json") //设置200状态 w.WriteHeader(http.StatusOK) arr := returnFormat{ Code:code, Msg:msg, Data:data, } //将结构体转化成json字符串 ret,err := json.Marshal(arr) if err!=nil{ log.Println(err.Error()) } //输出 w.Write(ret) }