package api import ( "encoding/json" "log" "net/http" "strconv" "strings" ) const ( Error_code = 0 Error_code_1001 = 1001 Error_msg_1001 = "需要登录" Error_code_1002 = 1002 Error_msg_1002 = "缺失参数" Error_code_1003 = 1003 Error_msg_1003 = "无效参数" Error_code_1004 = 1004 Error_msg_1004 = "没有权限" Error_code_1005 = 1005 Error_msg_1005 = "请求方式有误" ) var R = &r{} type M map[string]interface{} type r struct{} //校验是否缺少请求参数 func (r *r) CheckReqParam(w http.ResponseWriter, req *http.Request, keys ...string) bool { msg := Error_msg_1002 array := []string{} for _, v := range keys { if len(req.Form[v]) > 0 { continue } array = append(array, v) } if len(array) > 0 { msg += strings.Join(array, ",") log.Println(msg) r.ServeJson(w, req, &Result{ Error_code: Error_code_1002, Error_msg: msg, }) return false } return true } //无效参数 func (r *r) InvalidReqParam(w http.ResponseWriter, req *http.Request, args ...string) string { msg := Error_msg_1003 + strings.Join(args, ",") r.ServeJson(w, req, &Result{ Error_code: Error_code_1003, Error_msg: msg, }) log.Println(msg) return msg } //没有权限 func (r *r) NoPermissionReq(w http.ResponseWriter, req *http.Request, args ...string) string { msg := Error_msg_1004 if len(args) >= 0 { msg += "," } msg += strings.Join(args, ",") r.ServeJson(w, req, &Result{ Error_code: Error_code_1004, Error_msg: msg, }) log.Println(msg) return msg } func (r *r) ServeJson(w http.ResponseWriter, req *http.Request, result *Result) { content, err := json.MarshalIndent(result, "", " ") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Length", strconv.Itoa(len(content))) w.Header().Set("Content-Type", "application/json") w.Write(content) } func NewResult(data interface{}, err error) Result { errCode := 0 errMsg := "" if err != nil { errCode = -1 errMsg = err.Error() } return Result{ Error_code: errCode, Error_msg: errMsg, Data: data, } } //接口统一返回值 type Result struct { Error_code int `json:"error_code"` Error_msg string `json:"error_msg"` Data interface{} `json:"data"` }