|
@@ -0,0 +1,92 @@
|
|
|
+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 = "没有权限"
|
|
|
+)
|
|
|
+
|
|
|
+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)
|
|
|
+}
|
|
|
+
|
|
|
+//接口统一返回值
|
|
|
+type Result struct {
|
|
|
+ Error_code int `json:"error_code"`
|
|
|
+ Error_msg string `json:"error_msg"`
|
|
|
+ Data interface{} `json:"data"`
|
|
|
+}
|