多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] ### 核心api ***** 请求格式和处理函数绑定 ``` func HandleFunc( pattern string,//请求对格式,如http://localhost/user/login handler func(ResponseWriter, *Request)//处理函数 ) ``` 启动服务器 ``` func ListenAndServe( addr string,//地址如:8080 handler Handler // ) ``` 创建返回数据的结构体 ``` type H struct { Code int `json:"code"` Msg string `json:"msg"` Data interface{}`json:"data, omitempty"` } `json:"code"`的意思是把json字符串里的key(Code)变为小写 `json:"data, omitempty"`的意思是如果该字段值为空,则不显示 ``` ### 正式代码 ***** ``` package main import ( "encoding/json" "fmt" "io" "log" "net/http" ) func userLogin(writer http.ResponseWriter, request * http.Request) { request.ParseForm() mobile := request.PostForm.Get("mobile") passwd := request.PostForm.Get("passwd") fmt.Println("mobile=",mobile,";passwd=", passwd) loginok := false if mobile == "12" && passwd == "123" { loginok = true } //str := `{"code":0, "data": {"id","1", "token":"test"}` if loginok { data := make(map[string]interface{ }) data["id"] = 1 data["token"] = "test" Resp(writer, 0, data, "") }else { Resp(writer, -1, nil, "密码不正确") } _, _ = io.WriteString(writer, "hello world") } type H struct { Code int `json:"code"` Msg string `json:"msg"` Data interface{}`json:"data, omitempty"` } func Resp(w http.ResponseWriter, code int, data interface{}, msg string) { w.Header().Set("Content-Type", "application") w.WriteHeader(http.StatusOK) h := H{ Code: code, Msg: msg, Data: data, } //MARK:- 将结构体转化为输出 ret,err := json.Marshal(h) if err != nil { log.Println(err.Error()) } _, _ = w.Write(ret) //_, _ = w.Write([]byte(str)) } func main() { http.HandleFunc("/usr/login", userLogin) _ = http.ListenAndServe(":9090", nil) fmt.Println("hello world") } ```