作者 唐旭辉

错误处理跳转

## 目录
* [代码声明](#代码声明)
* [命名规范](#命名规范)
* [项目约定](#项目约定)
* [注意事项](#注意事项)
- [代码声明](#代码声明)
- [命名规范](#命名规范)
- [项目约定](#项目约定)
- [注意事项](#注意事项)
### 代码声明
... ... @@ -66,6 +67,7 @@ func Foo(){}
```
3.目录结构
```
* conf //配置
* dev.conf
... ... @@ -85,7 +87,7 @@ func Foo(){}
* static //静态数据
* views //视图
* main.go
* main.go
* Dockerfile
* README.md
* *.sh //脚本
... ... @@ -93,24 +95,24 @@ func Foo(){}
#### 项目约定
1. 入参跟返回值都要定义一个协议结构 protocol.XxxRequest *protocol.XxxResponse,方便扩展
1. 入参跟返回值都要定义一个协议结构 protocol.XxxRequest \*protocol.XxxResponse,方便扩展
2. 函数方法的变量都定义在函数的头几行 var( ... )
3. 服务调用尽量封装成接口,方便测试扩展 比如:ISmsServe{ Send() error }
4. 公用的基础代码库,需要做一下封装放在 [gocomm](http://gitlab.fjmaimaimai.com/mmm-go/gocomm) ,方便在其他项目中调用
4. 可以使用代码生成固定格式, [项目地址](http://gitlab.fjmaimaimai.com/mmm-go/gencode) 脚本:.\gencode.exe new -c Auth -m Login
4. 公用的基础代码库,需要做一下封装放在 [gocomm](http://gitlab.fjmaimaimai.com/mmm-go/gocomm) ,方便在其他项目中调用
5. 可以使用代码生成固定格式, [项目地址](http://gitlab.fjmaimaimai.com/mmm-go/gencode) 脚本:.\gencode.exe new -c Auth -m Login
```
package pkg
//Login
func(this *AuthController)Login(){
var msg *mybeego.Message
var msg *protocol.ResponseMessage
defer func(){
this.Resp(msg)
}()
var request *protocol.LoginRequest
if err:=json.Unmarshal(this.ByteBody,&request);err!=nil{
log.Error(err)
msg = mybeego.NewMessage(1)
msg = protocol.ReturnResponse(1)
return
}
if b,m :=this.Valid(request);!b{
... ... @@ -129,20 +131,18 @@ type LoginResponse struct {
func Login(request *protocol.LoginRequest)(rsp *protocol.LoginResponse,err error){
var (
)
rsp =&protocol.LoginResponse{}
return
}
```
#### 注意事项
1. 启动一个groutine(eg:go func(){}()),需要在函数内进行recover,不然groutine里面panic,会导致外部程序一起崩溃掉;
2. 当接受者是map, chan, func, 不要使用指针传递,因为它们本身就是引用类型
1. 启动一个 groutine(eg:go func(){}()),需要在函数内进行 recover,不然 groutine 里面 panic,会导致外部程序一起崩溃掉;
2. 当接受者是 map, chan, func, 不要使用指针传递,因为它们本身就是引用类型
3. 当接受者类型是一个结构体并且很庞大,或者是一个大数组,建议使用指针传递来提高性能,其他场景使用值传递即可
4. 当接受者是一个结构体,并且包含了sync.Mutex或者类似的用于同步的成员。必须使用指针传递,避免成员拷贝
4. 当接受者是一个结构体,并且包含了 sync.Mutex 或者类似的用于同步的成员。必须使用指针传递,避免成员拷贝
5. 当函数内部需要修改接受者,必须使用指针传递
6. 声明空的slice应该使用下面的格式: var t []string 不要使用 t := []string{} ,前者声明了一个nil slice而后者是一个长度为0的非nil的slice。
6. 声明空的 slice 应该使用下面的格式: var t []string 不要使用 t := []string{} ,前者声明了一个 nil slice 而后者是一个长度为 0 的非 nil 的 slice。
... ...
[dev]
#数据库相关
data_source = "root:123456@tcp(192.168.100.102:3306)/ability_display?loc=Local"
# data_source = "root:123456@tcp(192.168.100.102:3306)/ability_display?loc=Local"
#data_source = "root:sutianxia2015@tcp(115.29.205.99:3306)/ability_display"
data_source = "root:root@tcp(localhost:3306)/ability_display?loc=Local"
#redis相关配置
redis_add_port = "192.168.100.102:6379"
... ...
... ... @@ -47,42 +47,42 @@ func init() {
var DefaultController *BaseController = &BaseController{}
//Valid valid struct
func (this *BaseController) Valid(obj interface{}) (result bool, msg *mybeego.Message) {
func (this *BaseController) Valid(obj interface{}) (result bool, msg *protocol.ResponseMessage) {
/*校验*/
var err error
valid := validation.Validation{}
result, err = valid.Valid(obj)
if err != nil {
msg = mybeego.NewMessage(1)
msg = protocol.BadRequestParam(1)
return
}
if !result {
for _, err := range valid.Errors {
log.Error(err.Key, err.Message)
}
msg = mybeego.NewMessage(2)
msg = protocol.BadRequestParam(2)
return
}
return
}
//GenMessage genarate a response message
func (this *BaseController) GenMessage(rsp interface{}, err error) *mybeego.Message {
var msg *mybeego.Message
if err == nil {
msg = mybeego.NewMessage(0)
msg.Data = rsp
return msg
}
//log.Error(err)
if e, ok := err.(common.Error); ok {
msg = mybeego.NewMessage(e.Code)
msg.Data = rsp
return msg
}
msg = mybeego.NewMessage(1)
return msg
}
// func (this *BaseController) GenMessage(rsp interface{}, err error) *protocol.ResponseMessage {
// var msg *protocol.ResponseMessage
// if err == nil {
// msg = protocol.ReturnResponse(0)
// msg.Data = rsp
// return msg
// }
// //log.Error(err)
// if e, ok := err.(common.Error); ok {
// msg = protocol.ReturnResponse(e.Code)
// msg.Data = rsp
// return msg
// }
// msg = protocol.ReturnResponse(1)
// return msg
// }
//获取请求头信息
func GetRequestHeader(ctx *context.Context) *protocol.RequestHeader {
... ... @@ -149,7 +149,7 @@ func CheckSign(ctx *context.Context) (result bool) {
sha256.Write([]byte(sign))
signHex = hex.EncodeToString(sha256.Sum(nil))
if strings.Compare(signHex, h.Sign) != 0 {
msg := mybeego.NewMessage(113)
msg := protocol.BadRequestParam(113)
log.Error(fmt.Sprintf("%v req:%v resp:%v %v", ctx.Request.RequestURI, common.AssertJson(h), common.AssertJson(msg), signHex))
ctx.Output.JSON(msg, false, false)
result = false
... ... @@ -161,7 +161,7 @@ func CheckSign(ctx *context.Context) (result bool) {
//检查access_token
func CheckToken(ctx *context.Context) (result bool) {
var (
msg *mybeego.Message
msg *protocol.ResponseMessage
)
result = true
defer func() {
... ... @@ -172,7 +172,7 @@ func CheckToken(ctx *context.Context) (result bool) {
}()
token := ctx.Input.Header("x-mmm-accesstoken")
if rsp, err := auth.CheckToken(&protocol.CheckTokenRequest{Token: token}); err != nil || rsp.UserInfo == nil {
msg = DefaultController.GenMessage(rsp, err)
msg = protocol.NewReturnResponse(rsp, err)
log.Error(fmt.Sprintf("%v req:%v resp:%v", ctx.Request.RequestURI, token, common.AssertJson(msg)))
return
} else {
... ... @@ -187,7 +187,7 @@ func CheckToken(ctx *context.Context) (result bool) {
//检查Uuid
func CheckUuid(ctx *context.Context) (result bool) {
var (
msg *mybeego.Message
msg *protocol.ResponseMessage
)
result = true
defer func() {
... ... @@ -197,7 +197,7 @@ func CheckUuid(ctx *context.Context) (result bool) {
}
}()
uuid := ctx.Input.Header("x-mmm-uuid")
msg = DefaultController.GenMessage(auth.CheckUuid(&protocol.CheckUuidRequest{Uuid: uuid}))
msg = protocol.NewReturnResponse(auth.CheckUuid(&protocol.CheckUuidRequest{Uuid: uuid}))
if msg != nil {
log.Error(fmt.Sprintf("%v req:%v resp:%v", ctx.Request.RequestURI, uuid, common.AssertJson(msg)))
}
... ...
... ... @@ -8,7 +8,6 @@ import (
s_auth "ability/services/auth"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/mybeego"
)
var (
... ... @@ -22,99 +21,99 @@ type AuthController struct {
// Login
// @router /login [post]
func (this *AuthController) Login() {
var msg *mybeego.Message
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.LoginRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = mybeego.NewMessage(1)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
msg = this.GenMessage(auth.Login(request))
msg = protocol.NewReturnResponse(auth.Login(request))
}
//SmsCode
// @router /smsCode [post]
func (this *AuthController) SmsCode() {
var msg *mybeego.Message
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.SmsCodeRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = mybeego.NewMessage(1)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
msg = this.GenMessage(auth.SmsCode(request))
msg = protocol.NewReturnResponse(auth.SmsCode(request))
}
//UpdateDevice
// @router /updateDevice [post]
func (this *AuthController) UpdateDevice() {
var msg *mybeego.Message
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.UpdateDeviceRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = mybeego.NewMessage(1)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
msg = this.GenMessage(auth.UpdateDevice(request))
msg = protocol.NewReturnResponse(auth.UpdateDevice(request))
}
//AccessToken
// @router /accessToken [post]
func (this *AuthController) AccessToken() {
var msg *mybeego.Message
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.AccessTokenRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = mybeego.NewMessage(1)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
msg = this.GenMessage(auth.AccessToken(request))
msg = protocol.NewReturnResponse(auth.AccessToken(request))
}
//RefreshToken
// @router /refreshToken [post]
func (this *AuthController) RefreshToken() {
var msg *mybeego.Message
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.RefreshTokenRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = mybeego.NewMessage(1)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
msg = this.GenMessage(auth.RefreshToken(request))
msg = protocol.NewReturnResponse(auth.RefreshToken(request))
}
... ...
... ... @@ -6,7 +6,6 @@ import (
"ability/services/upload"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/mybeego"
)
type UploadController struct {
... ... @@ -17,7 +16,7 @@ type UploadController struct {
// @router /image [post]
func (this *UploadController) Image() {
var (
msg *mybeego.Message
msg *protocol.ResponseMessage
err error
)
defer func() {
... ... @@ -26,7 +25,7 @@ func (this *UploadController) Image() {
var request = &protocol.FileRequest{}
//if err:=json.Unmarshal(this.ByteBody,&request);err!=nil{
// log.Error(err)
// msg = mybeego.NewMessage(1)
// msg = protocol.ReturnResponse(1)
// return
//}
//if b,m :=this.Valid(request);!b{
... ... @@ -37,14 +36,14 @@ func (this *UploadController) Image() {
log.Error(err)
return
}
msg = this.GenMessage(upload.Image(request))
msg = protocol.NewReturnResponse(upload.Image(request))
}
// Image
// @router /voice [post]
func (this *UploadController) Voice() {
var (
msg *mybeego.Message
msg *protocol.ResponseMessage
err error
)
defer func() {
... ... @@ -53,7 +52,7 @@ func (this *UploadController) Voice() {
var request = &protocol.FileRequest{}
//if err:=json.Unmarshal(this.ByteBody,&request);err!=nil{
// log.Error(err)
// msg = mybeego.NewMessage(1)
// msg = protocol.ReturnResponse(1)
// return
//}
//if b,m :=this.Valid(request);!b{
... ... @@ -64,5 +63,5 @@ func (this *UploadController) Voice() {
log.Error(err)
return
}
msg = this.GenMessage(upload.Voice(request))
msg = protocol.NewReturnResponse(upload.Voice(request))
}
... ...
package v1
import (
"ability/protocol"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/mybeego"
)
... ... @@ -23,17 +25,17 @@ func (this *UserController) URLMapping() {
// @Param body body string true "body"
// @router /v1/user/login [post]
func (this *UserController) Login() {
var msg *mybeego.Message
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
msg = mybeego.NewErrMessage(0, "login success")
msg = protocol.NewReturnResponse("login success", nil)
}
func (this *UserController) Logout() {
var msg *mybeego.Message
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
msg = mybeego.NewErrMessage(0, "logout success")
msg = protocol.NewReturnResponse("logout success", nil)
}
... ...
... ... @@ -8,7 +8,6 @@ import (
"ability/services/version"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/mybeego"
)
type VersionController struct {
... ... @@ -17,19 +16,19 @@ type VersionController struct {
//GetLatestVersionInfo
func (this *VersionController) GetLatestVersionInfo() {
var msg *mybeego.Message
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.GetLatestVersionInfoRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = mybeego.NewMessage(1)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
msg = this.GenMessage(version.GetLatestVersionInfo(request))
msg = protocol.NewReturnResponse(version.GetLatestVersionInfo(request))
}
... ...
... ... @@ -23,7 +23,7 @@ var errmessge ErrorMap = map[int]string{
func SearchErr(code int) ErrorCode {
return errmessge.Search(code)
}
func ReturnResponse(data interface{}, eRR error) *ResponseMessage {
func NewReturnResponse(data interface{}, eRR error) *ResponseMessage {
var msg *ResponseMessage
if eRR == nil {
msg = NewMesage(0)
... ... @@ -37,6 +37,10 @@ func ReturnResponse(data interface{}, eRR error) *ResponseMessage {
return NewMesage(1)
}
func BadRequestParam(code int) *ResponseMessage {
return NewMesage(code)
}
func InitMessageCode() {
// messages := []struct {
// Code int
... ...
... ... @@ -60,7 +60,7 @@ func (s *AuthService) Login(request *protocol.LoginRequest) (rsp *protocol.Login
user, err = UserRepository.GetUsersByMobile(request.Phone)
if err != nil {
log.Error(err)
err = common.NewError(2020, err) //账号不存在
err = protocol.NewErrWithMessage(2020, err) //账号不存在
return
}
switch request.GrantType {
... ... @@ -68,7 +68,7 @@ func (s *AuthService) Login(request *protocol.LoginRequest) (rsp *protocol.Login
if strings.Compare(user.Password, request.PassWord) == 0 {
goto Success
} else {
err = common.NewError(2021, err) //登录密码错误
err = protocol.NewErrWithMessage(2021, err) //登录密码错误
return
}
break
... ... @@ -169,15 +169,15 @@ func (s *AuthService) Login1(request *protocol.LoginRequest) (rsp *protocol.Logi
Name: useridentity.Uname,
Icon: useridentity.Icon,
}
rsp, err := s_im.ParseUserUpdateUinfo(v)
imRsp, err := s_im.ParseUserUpdateUinfo(v)
if err != nil {
log.Error("s_im.ParseUserUpdateUinfo err:", err)
}
if err == nil {
if rsp.Code == 200 {
if imRsp.Code == 200 {
break
} else {
log.Error("s_im.ParseUserUpdateUinfo response code:", rsp.Code)
log.Error("s_im.ParseUserUpdateUinfo response code:", imRsp.Code)
}
}
}
... ... @@ -198,12 +198,12 @@ func (s *AuthService) AccessToken(request *protocol.AccessTokenRequest) (rsp *pr
)
_, err = ConfigRepository.GetCfgClient(request.ClientId, request.ClientSecret)
if err != nil {
err = common.NewError(101, err)
err = protocol.NewErrWithMessage(101, err)
return
}
userInfo, err = UserRepository.GetUserInfoByAuthCode(request.AuthCode)
if err != nil {
err = common.NewError(4139, err)
err = protocol.NewErrWithMessage(4139, err)
return
}
userInfo.AccessToken = uid.NewV1().StringNoDash()
... ... @@ -228,12 +228,12 @@ func (s *AuthService) RefreshToken(request *protocol.RefreshTokenRequest) (rsp *
)
_, err = ConfigRepository.GetCfgClient(request.ClientId, request.ClientSecret)
if err != nil {
common.NewError(101, err)
protocol.NewErrWithMessage(101, err)
return
}
userInfo, err = UserRepository.GetUserInfoByRefreshToken(request.RefreshToken)
if err != nil {
common.NewError(4139, err)
protocol.NewErrWithMessage(4139, err)
return
}
userInfo.AccessToken = uid.NewV1().StringNoDash()
... ... @@ -267,7 +267,7 @@ func (s *AuthService) CheckToken(request *protocol.CheckTokenRequest) (rsp *prot
}
userInfo, err = models.GetUserInfoByToken(request.Token)
if err != nil {
err = common.NewError(4141, err)
err = protocol.NewErrWithMessage(4141, err)
return
}
rsp = &protocol.CheckTokenResponse{
... ...
... ... @@ -6,7 +6,6 @@ import (
"strings"
"time"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/common"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
)
... ... @@ -69,11 +68,11 @@ func (o LoginByPassword) LoginAuth() (*UserIdentity, error) {
user, err := UserRepository.GetUserInfoByMobile(o.Username)
if err != nil {
log.Error(err)
o.err = common.NewError(2020, err) //账号不存在
o.err = protocol.NewErrWithMessage(2020, err) //账号不存在
return nil, o.err
}
if strings.Compare(user.Passwd, o.Password) != 0 {
o.err = common.NewError(2021, err) //登录密码错误
o.err = protocol.NewErrWithMessage(2021, err) //登录密码错误
return nil, o.err
}
identity := &UserIdentity{
... ... @@ -91,7 +90,7 @@ func (o LoginBySms) LoginAuth() (*UserIdentity, error) {
user, err := UserRepository.GetUserInfoByMobile(o.Phone)
if err != nil {
log.Error(err)
o.err = common.NewError(2020, err) //账号不存在
o.err = protocol.NewErrWithMessage(2020, err) //账号不存在
return nil, o.err
}
result, err := CheckSmsCode(o.Phone, o.Code, protocol.SmsLoginCode)
... ...
... ... @@ -7,14 +7,14 @@ package user
// "ability/models"
//)
//
//func GetUserList(mobile string)*mybeego.Message{
//func GetUserList(mobile string)*protocol.ResponseMessage{
// u,err:=models.GetUserByMobile(mobile)
// if err!=nil{
// log.Error(err)
// log.Error(mobile)
// return mybeego.NewErrMessage(1)
// }
// msg :=mybeego.NewMessage(0)
// msg :=protocol.ReturnResponse(0)
// msg.Data = u
// return msg
//}
... ...
package websocket
import (
"net/http"
"strconv"
"github.com/gorilla/websocket"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/mybeego"
ws "gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/websocket"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"net/http"
"strconv"
)
var upgrader = websocket.Upgrader{}
... ... @@ -20,10 +21,11 @@ func Upgrage(w http.ResponseWriter, r *http.Request) {
if err != nil {
log.Fatal(err)
}
wsConn := ws.NewWebsocketConnection(conn, requestHead, WsOnReceive)
wsConn.Serve()
}
func WsOnReceive(data []byte) *mybeego.Message {
return mybeego.NewMessage(0)
}
\ No newline at end of file
}
... ...