diff --git a/handle/error.go b/handle/error.go index 644eb82..828d52f 100644 --- a/handle/error.go +++ b/handle/error.go @@ -8,7 +8,7 @@ import ( "github.com/xmdhs/authlib-skin/model" ) -func handleError(ctx context.Context, w http.ResponseWriter, msg string, code int, httpcode int) { +func handleError(ctx context.Context, w http.ResponseWriter, msg string, code model.APIStatus, httpcode int) { w.WriteHeader(httpcode) b, err := json.Marshal(model.API[any]{Code: code, Msg: msg, Data: nil}) if err != nil { diff --git a/handle/user.go b/handle/user.go index 2477f74..0e95eb1 100644 --- a/handle/user.go +++ b/handle/user.go @@ -1,25 +1,35 @@ package handle import ( + "database/sql" "log/slog" "net/http" + "github.com/bwmarrin/snowflake" "github.com/go-playground/validator/v10" "github.com/julienschmidt/httprouter" + "github.com/xmdhs/authlib-skin/config" "github.com/xmdhs/authlib-skin/db/mysql" "github.com/xmdhs/authlib-skin/model" + "github.com/xmdhs/authlib-skin/service" "github.com/xmdhs/authlib-skin/utils" ) -func Reg(l *slog.Logger, q mysql.Querier, v *validator.Validate) httprouter.Handle { +func Reg(l *slog.Logger, q mysql.Querier, v *validator.Validate, db *sql.DB, snow *snowflake.Node, c config.Config) httprouter.Handle { return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { ctx := r.Context() u, err := utils.DeCodeBody[model.User](r.Body, v) if err != nil { l.InfoContext(ctx, err.Error()) + handleError(ctx, w, err.Error(), model.ErrInput, 400) + return + } + err = service.Reg(ctx, u, q, db, snow, c) + if err != nil { + l.WarnContext(ctx, err.Error()) + handleError(ctx, w, err.Error(), model.ErrService, 500) + return } - _ = u - } } diff --git a/model/const.go b/model/const.go index 05d35f3..e0c78ea 100644 --- a/model/const.go +++ b/model/const.go @@ -1,5 +1,9 @@ package model +type APIStatus int + const ( - OK = 0 + OK APIStatus = iota + ErrInput + ErrService ) diff --git a/model/model.go b/model/model.go index 75e1c1d..64b209c 100644 --- a/model/model.go +++ b/model/model.go @@ -1,9 +1,9 @@ package model type API[T any] struct { - Code int `json:"code"` - Data T `json:"data"` - Msg string `json:"msg"` + Code APIStatus `json:"code"` + Data T `json:"data"` + Msg string `json:"msg"` } type User struct {