Skip to content

Commit

Permalink
modify"
Browse files Browse the repository at this point in the history
  • Loading branch information
zheng.li committed Jan 4, 2021
1 parent 1442018 commit 8839be1
Show file tree
Hide file tree
Showing 43 changed files with 103 additions and 64 deletions.
44 changes: 31 additions & 13 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,25 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/go-playground/validator/v10"
"github.com/gozelus/zelus_rest/logger"
"github.com/pkg/errors"
"io"
"math"
"net/http"
"strings"
"sync"

"github.com/go-playground/validator/v10"
"github.com/gozelus/zelus_rest/logger"
"github.com/pkg/errors"

"github.com/google/uuid"
)

// abortIndex 一个极大值
// 一定比 handlers 数量大,导致 next 函数执行中断
const abortIndex int8 = math.MaxInt8 / 2

var _ Context = &contextImp{}

type contextImp struct {
context.Context
request *http.Request
Expand Down Expand Up @@ -52,19 +55,34 @@ func (c *contextImp) init(w http.ResponseWriter, req *http.Request) {
c.requestID = strings.Replace(uuid.Must(uuid.NewRandom()).String(), "-", "", -1)
c.index = -1
}
func (c *contextImp) RenderJSON(r Rsp) {
_ = c.renderJSON(r.ErrorCode(), struct {
Code int `json:"error_code"`
Message string `json:"error_message"`
RequestID string `json:"request_id"`
Data interface{} `json:"data"`
func (c *contextImp) RenderOkJSON(data interface{}) {
_ = c.renderJSON(http.StatusOK, struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data"`
}{
Code: r.ErrorCode(),
Message: r.ErrorMessage(),
RequestID: c.requestID,
Data: r.Data(),
Code: 200,
Message: "success",
Data: data,
})
}

func (c *contextImp) RenderErrorJSON(data interface{}, err error) {
var theError StatusError = statusInternalServerError
if val, ok := err.(StatusError); ok {
theError = val
}
_ = c.renderJSON(theError.GetCode(), struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data"`
}{
Code: theError.GetCode(),
Message: theError.GetMessage(),
Data: data,
})
}

func (c *contextImp) Headers() map[string][]string {
return c.request.Header
}
Expand Down
41 changes: 13 additions & 28 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,51 +4,36 @@ import "net/http"

// 一些预定好的错误
var (
statusMethodNotAllowed = rsp{
statusMethodNotAllowed = &statusError{
RCode: http.StatusMethodNotAllowed,
RMessage: "method not allowed",
}
statusNotFound = rsp{
statusNotFound = &statusError{
RCode: http.StatusNotFound,
RMessage: "not found",
}
statusInternalServerError = rsp{
statusInternalServerError = &statusError{
RCode: http.StatusInternalServerError,
RMessage: "internal server error",
}
statusBadRequest = rsp{
RCode: http.StatusBadRequest,
RMessage: "bad request",
}
)

type rsp struct {
type statusError struct {
RCode int
RMessage string
RData interface{}
}

var _ Rsp = rsp{}

func (r rsp) ErrorCode() int {
return r.RCode
}
func (r rsp) ErrorMessage() string {
return r.RMessage
}
func (r rsp) Data() interface{} {
return r.RData
func (s statusError) Error() string {
return s.RMessage
}

func StatusMethodNotAllowedResp() Rsp {
return statusMethodNotAllowed
func (s statusError) GetCode() int {
return s.RCode
}
func StatusNotFoundResp() Rsp {
return statusNotFound
}
func StatusInternalServerErrorResp() Rsp {
return statusInternalServerError
}
func StatusBadRequestResp() Rsp {
return statusBadRequest

func (s statusError) GetMessage() string {
return s.RMessage
}

var _ StatusError = &statusError{}
1 change: 1 addition & 0 deletions example/id_generator/api/errors/code.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package apiErrors
1 change: 1 addition & 0 deletions example/id_generator/api/errors/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package errors
1 change: 1 addition & 0 deletions example/id_generator/api/vars.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package api
1 change: 1 addition & 0 deletions example/id_generator/cmd/id_generator.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package cmd
1 change: 1 addition & 0 deletions example/id_generator/controllers/v1/id.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package v1
1 change: 1 addition & 0 deletions example/id_generator/routes/routes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package routes
1 change: 1 addition & 0 deletions example/id_generator/service/id_generator.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package service
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ package model

import (
"errors"
"time"

"github.com/gozelus/zelus_rest"
"github.com/gozelus/zelus_rest/core/db"
"github.com/gozelus/zelus_rest/example/internal/biz/repos"
"github.com/gozelus/zelus_rest/example/internal/data/db"
"gorm.io/gorm"
"time"
)

type User struct {
Expand Down Expand Up @@ -35,14 +36,35 @@ func (u *User) Update() error {
func (u *User) Save(ctx rest.Context) error {
var err error
if u.ID == 0 && len(u.Phone) > 0 {
u.ID = time.Now().Unix()
tx := u.db.Begin()
bind := &models.UserBindsModel{}
if bind, err = u.bindRepo.FindOneWithBindCodeBindTypeByTx(ctx, tx, u.Phone, 1); err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
tx.Rollback()
return err
}

}
}
func (u *User) RegisterOrLoginByPhone(ctx rest.Context) error {
u.ID = time.Now().Unix()
tx := u.db.Begin()
var err error
bind := &models.UserBindsModel{}
if bind, err = u.bindRepo.FindOneWithBindCodeBindTypeByTx(ctx, tx, u.Phone, 1); err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
tx.Rollback()
return err
}

// gorm.ErrRecordNotFound
// create bind and userinfo
if err := u.bindRepo.InsertByTx(ctx, tx, bind); err != nil {
tx.Rollback()
return err
}

userInfo := &models.UsersModel{
Id: u.ID,
Nickname: u.NickName,
Avatar: u.AvatarGuid,
}
if err := u.userInfoRepo.InsertByTx(ctx,tx, userInfo);err!=nil{
tx.Rollback()
return err
}
}
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
2 changes: 1 addition & 1 deletion route.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,6 @@ func (r *routerz) search(method, path string) (HandlerFunc, error) {
}
}
return func(context Context) {
context.RenderJSON(statusNotFound)
context.RenderErrorJSON(nil, statusNotFound)
}, nil
}
33 changes: 20 additions & 13 deletions type.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,14 @@ import (
)

type (
// StatusError
// 用于拓展错误,GetCode 返回值将会作为 httpCode
StatusError interface {
error
GetCode() int
GetMessage() string
}

// handlerFund 定义实际处理请求的函数
HandlerFunc func(Context)

Expand All @@ -20,17 +28,6 @@ type (
Handler HandlerFunc
}

// ErrorInterface 用于扩展 Error
Rsp interface {
// ErrorCode 此方法的返回值将会作为 http code
// 也会映射为结构体中的 error_code 字段
ErrorCode() int
// ErrorMessage 映射为返回结构体中的 error_message 字段
ErrorMessage() string
// Data
Data() interface{}
}

Context interface {
context.Context

Expand All @@ -41,7 +38,17 @@ type (
JSONQueryBind(v interface{}) error

Next()
RenderJSON(Rsp)

// RenderOkJSON
// 表示成功处理请求,返回 HttpStatusOk
RenderOkJSON(data interface{})

// RenderErrorJSON
// 内部尝试断言 error 为 StatusError,若断言成功
// HttpCode 会使用此 error 的 GetCode 返回值
// 若不成功,会使用 InternalServerErrorCode
RenderErrorJSON(data interface{}, err error)

GetRequestID() string
Set(string, interface{})
Get(string) (interface{}, bool)
Expand Down Expand Up @@ -102,7 +109,7 @@ func NewServer(host string, port int, opts ...Option) Server {
defer func() {
if err := recover(); err != nil {
logger.ErrorfWithStackWithContext(c, "recover err : %s", err)
c.RenderJSON(statusInternalServerError)
c.RenderErrorJSON(statusInternalServerError)
}
}()
c.Next()
Expand Down

0 comments on commit 8839be1

Please sign in to comment.