add: user auth accomplished
This commit is contained in:
@@ -4,29 +4,93 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"juwan-backend/app/users/api/internal/contextx"
|
||||
"juwan-backend/common/utils"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/zeromicro/go-zero/rest/httpx"
|
||||
"juwan-backend/app/users/api/internal/logic/user"
|
||||
"juwan-backend/app/users/api/internal/svc"
|
||||
"juwan-backend/app/users/api/internal/types"
|
||||
|
||||
"github.com/zeromicro/go-zero/rest/httpx"
|
||||
)
|
||||
|
||||
// 用户注册接口
|
||||
func RegisterHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := normalizeRegisterBody(r); err != nil {
|
||||
httpx.ErrorCtx(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
|
||||
var req types.RegisterReq
|
||||
if err := httpx.Parse(r, &req); err != nil {
|
||||
httpx.ErrorCtx(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
|
||||
l := user.NewRegisterLogic(r.Context(), svcCtx)
|
||||
requestId := r.Header.Get("X-Request-ID")
|
||||
//regCtx := context.WithValue(r.Context(), "request_id", requestId)
|
||||
regCtx := contextx.WithRequestId(r.Context(), requestId)
|
||||
if requestId == "" {
|
||||
httpx.ErrorCtx(r.Context(), w, errors.New("bad request"))
|
||||
}
|
||||
|
||||
l := user.NewRegisterLogic(regCtx, svcCtx)
|
||||
resp, err := l.Register(&req)
|
||||
|
||||
if err != nil {
|
||||
httpx.ErrorCtx(r.Context(), w, err)
|
||||
} else {
|
||||
httpx.OkJsonCtx(r.Context(), w, resp)
|
||||
httpx.OkJsonCtx(r.Context(), w, utils.NewErrorResp(400, err))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeRegisterBody(r *http.Request) error {
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
if len(body) == 0 {
|
||||
r.Body = io.NopCloser(bytes.NewReader(body))
|
||||
return nil
|
||||
}
|
||||
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
r.Body = io.NopCloser(bytes.NewReader(body))
|
||||
return nil
|
||||
}
|
||||
|
||||
vcode, exists := payload["vcode"]
|
||||
if exists {
|
||||
switch value := vcode.(type) {
|
||||
case string:
|
||||
parsed, convErr := strconv.Atoi(value)
|
||||
if convErr != nil {
|
||||
return fmt.Errorf("invalid vcode format")
|
||||
}
|
||||
payload["vcode"] = parsed
|
||||
case float64:
|
||||
payload["vcode"] = int(value)
|
||||
}
|
||||
}
|
||||
|
||||
normalized, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
r.Body = io.NopCloser(bytes.NewReader(normalized))
|
||||
r.ContentLength = int64(len(normalized))
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user