2 Star 3 Fork 1

Allen / go-scaffold

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
response.go 2.05 KB
一键复制 编辑 原始数据 按行查看 历史
Allen 提交于 2020-08-25 16:02 . add http server
package server
import (
"net/http"
)
// RESPONSE dict
var RESPONSE = make(map[int]interface{}, 12)
// Response TL;DR
type Response struct {
Data interface{} `json:"data"`
Code int `json:"code"`
ErrorNo int `json:"err_no"`
Msg string `json:"msg"`
}
func init() {
RESPONSE[http.StatusOK] = map[string]interface{}{"err_no": 0, "msg": "请求成功"}
RESPONSE[http.StatusCreated] = map[string]interface{}{"err_no": 0, "msg": "操作成功"}
RESPONSE[http.StatusAccepted] = map[string]interface{}{"err_no": 0, "msg": "数据接收成功"}
RESPONSE[http.StatusConflict] = map[string]interface{}{"err_no": 0, "msg": "重复请求"}
RESPONSE[http.StatusBadRequest] = map[string]interface{}{"err_no": 10001, "msg": "请求参数错误"}
RESPONSE[http.StatusUnauthorized] = map[string]interface{}{"err_no": 10002, "msg": "无权限访问系统"}
RESPONSE[http.StatusForbidden] = map[string]interface{}{"err_no": 10003, "msg": "禁止访问"}
RESPONSE[http.StatusNotFound] = map[string]interface{}{"err_no": 10004, "msg": "未匹配到数据"}
RESPONSE[http.StatusMethodNotAllowed] = map[string]interface{}{"err_no": 10005, "msg": "请求方法不支持"}
RESPONSE[http.StatusPreconditionFailed] = map[string]interface{}{"err_no": 10006, "msg": "参数类型错误"}
RESPONSE[http.StatusRequestedRangeNotSatisfiable] = map[string]interface{}{"err_no": 10007, "msg": "数据不允许修改"}
RESPONSE[http.StatusInternalServerError] = map[string]interface{}{"err_no": 10008, "msg": "服务器异常"}
}
func formatStatus(status int) (int, string) {
if _, ok := RESPONSE[status]; ok {
resp := RESPONSE[status].(map[string]interface{})
return resp["err_no"].(int), resp["msg"].(string)
}
return -1, "超出定义的状态码"
}
// FormatResponse transfer status code to response message
// return status code, map of response data
func FormatResponse(status int, data interface{}) (int, *Response) {
errNo, msg := formatStatus(status)
resp := &Response{
Data: data,
Code: status,
ErrorNo: errNo,
Msg: msg,
}
return status, resp
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/zakums06/go-scaffold.git
git@gitee.com:zakums06/go-scaffold.git
zakums06
go-scaffold
go-scaffold
v0.1.15

搜索帮助

344bd9b3 5694891 D2dac590 5694891