[Go] go语言gin框架封装返回的错误码类
作者:互联网
当需要接口返回错误信息的时候
尽量不要硬编码在接口返回对方
可以封装一个错误码类
类似下面这样
演示
types/api_code.go
package types type Codes struct { SUCCESS uint FAILED uint CnMessage map[uint]string EnMessage map[uint]string LANG string } var ApiCode = &Codes{ SUCCESS: 20000, FAILED: 40000, LANG: "cn", } func init() { ApiCode.CnMessage = map[uint]string{ ApiCode.SUCCESS: "操作成功", ApiCode.FAILED: "操作失败", } ApiCode.EnMessage = map[uint]string{ ApiCode.SUCCESS: "succeed", ApiCode.FAILED: "failed", } } func (c *Codes) GetMessage(code uint) string { if c.LANG == "cn" { message, ok := c.CnMessage[code] if !ok { return "" } return message } else { message, ok := c.EnMessage[code] if !ok { return "" } return message } }
测试使用
package types import "testing" func TestApiCode(t *testing.T) { t.Log(ApiCode.GetMessage(ApiCode.SUCCESS)) }
标签:map,string,SUCCESS,错误码,ApiCode,Go,uint,go,message 来源: https://www.cnblogs.com/taoshihan/p/15234084.html