Compare commits

..

2 Commits

Author SHA1 Message Date
vipg
66c1ee9620 add 2026-02-09 17:55:56 +08:00
vipg
cc8dfdad80 add 2026-02-09 17:54:46 +08:00
4 changed files with 84 additions and 34 deletions

View File

@@ -6,6 +6,7 @@ import (
"strings" "strings"
"common/auth" "common/auth"
"common/logger"
) )
type userIDKey struct{} type userIDKey struct{}
@@ -15,13 +16,15 @@ func AuthRequired() func(http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ah := r.Header.Get("Authorization") ah := r.Header.Get("Authorization")
if ah == "" || !strings.HasPrefix(ah, "Bearer ") { if ah == "" || !strings.HasPrefix(ah, "Bearer ") {
Unauthorized(w, "unauthorized") logger.WithPrefix("rid="+RequestIDFromContext(r)).Printf("auth missing header path=%s", r.URL.Path)
Unauthorized(w, r, "unauthorized")
return return
} }
token := strings.TrimSpace(strings.TrimPrefix(ah, "Bearer ")) token := strings.TrimSpace(strings.TrimPrefix(ah, "Bearer "))
sub, err := auth.ParseToken(token) sub, err := auth.ParseToken(token)
if err != nil || sub == "" { if err != nil || sub == "" {
Unauthorized(w, "unauthorized") logger.WithPrefix("rid="+RequestIDFromContext(r)).Printf("auth invalid token path=%s", r.URL.Path)
Unauthorized(w, r, "unauthorized")
return return
} }
ctx := context.WithValue(r.Context(), userIDKey{}, sub) ctx := context.WithValue(r.Context(), userIDKey{}, sub)

View File

@@ -14,30 +14,42 @@ func WriteJSON(w http.ResponseWriter, status int, ok bool, msg string, data inte
json.NewEncoder(w).Encode(types.Response{Status: ok, Message: msg, Data: data}) json.NewEncoder(w).Encode(types.Response{Status: ok, Message: msg, Data: data})
} }
func OK(w http.ResponseWriter, data interface{}) { func OK(w http.ResponseWriter, r *http.Request, data interface{}) {
WriteJSON(w, http.StatusOK, true, string(codes.OK), data) WriteJSON(w, http.StatusOK, true, string(codes.OK), addRequestID(r, data))
} }
func Created(w http.ResponseWriter, data interface{}) { func Created(w http.ResponseWriter, r *http.Request, data interface{}) {
WriteJSON(w, http.StatusCreated, true, string(codes.OK), data) WriteJSON(w, http.StatusCreated, true, string(codes.OK), addRequestID(r, data))
} }
func BadRequest(w http.ResponseWriter, msg string) { func BadRequest(w http.ResponseWriter, r *http.Request, msg string) {
WriteJSON(w, http.StatusBadRequest, false, msg, map[string]string{"code": string(codes.InvalidInput)}) WriteJSON(w, http.StatusBadRequest, false, msg, addRequestID(r, map[string]string{"code": string(codes.InvalidInput)}))
} }
func Unauthorized(w http.ResponseWriter, msg string) { func Unauthorized(w http.ResponseWriter, r *http.Request, msg string) {
WriteJSON(w, http.StatusUnauthorized, false, msg, map[string]string{"code": string(codes.Unauthorized)}) WriteJSON(w, http.StatusUnauthorized, false, msg, addRequestID(r, map[string]string{"code": string(codes.Unauthorized)}))
} }
func Conflict(w http.ResponseWriter, msg string) { func Conflict(w http.ResponseWriter, r *http.Request, msg string) {
WriteJSON(w, http.StatusConflict, false, msg, map[string]string{"code": string(codes.Conflict)}) WriteJSON(w, http.StatusConflict, false, msg, addRequestID(r, map[string]string{"code": string(codes.Conflict)}))
} }
func MethodNotAllowed(w http.ResponseWriter, msg string) { func MethodNotAllowed(w http.ResponseWriter, r *http.Request, msg string) {
WriteJSON(w, http.StatusMethodNotAllowed, false, msg, map[string]string{"code": string(codes.MethodNotAllowed)}) WriteJSON(w, http.StatusMethodNotAllowed, false, msg, addRequestID(r, map[string]string{"code": string(codes.MethodNotAllowed)}))
} }
func InternalError(w http.ResponseWriter) { func InternalError(w http.ResponseWriter, r *http.Request) {
WriteJSON(w, http.StatusInternalServerError, false, string(codes.InternalError), map[string]string{"code": string(codes.InternalError)}) WriteJSON(w, http.StatusInternalServerError, false, string(codes.InternalError), addRequestID(r, map[string]string{"code": string(codes.InternalError)}))
}
func addRequestID(r *http.Request, data interface{}) interface{} {
rid := RequestIDFromContext(r)
if m, ok := data.(map[string]string); ok {
m["request_id"] = rid
return m
}
if data == nil {
return map[string]string{"request_id": rid}
}
return map[string]interface{}{"request_id": rid, "data": data}
} }

View File

@@ -3,6 +3,7 @@ package logger
import ( import (
"log" "log"
"os" "os"
"fmt"
) )
type Logger interface { type Logger interface {
@@ -30,3 +31,18 @@ func SetLogger(l Logger) {
defaultLogger = l defaultLogger = l
} }
} }
type prefLogger struct {
prefix string
}
func (p *prefLogger) Printf(format string, v ...any) {
defaultLogger.Printf("%s %s", p.prefix, fmt.Sprintf(format, v...))
}
func (p *prefLogger) Fatalf(format string, v ...any) {
defaultLogger.Fatalf("%s %s", p.prefix, fmt.Sprintf(format, v...))
}
func WithPrefix(prefix string) Logger {
return &prefLogger{prefix: prefix}
}

View File

@@ -6,6 +6,7 @@ import (
"common/httpx" "common/httpx"
"common/codes" "common/codes"
"common/logger"
"user/internal/model" "user/internal/model"
"user/internal/service" "user/internal/service"
) )
@@ -20,74 +21,92 @@ func New(s *service.Service) *Handler {
func (h *Handler) Register(w http.ResponseWriter, r *http.Request) { func (h *Handler) Register(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost { if r.Method != http.MethodPost {
httpx.MethodNotAllowed(w, string(codes.MethodNotAllowed)) logger.WithPrefix("rid="+httpx.RequestIDFromContext(r)).Printf("method not allowed path=%s", r.URL.Path)
httpx.MethodNotAllowed(w, r, string(codes.MethodNotAllowed))
return return
} }
var req model.RegisterReq var req model.RegisterReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil { if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
httpx.BadRequest(w, "invalid json") logger.WithPrefix("rid="+httpx.RequestIDFromContext(r)).Printf("invalid json path=%s", r.URL.Path)
httpx.BadRequest(w, r, "invalid json")
return return
} }
userID, token, err := h.S.Register(req.Account, req.Password) userID, token, err := h.S.Register(req.Account, req.Password)
if err != nil { if err != nil {
switch err { switch err {
case service.ErrInvalidInput: case service.ErrInvalidInput:
httpx.BadRequest(w, "invalid account or password") logger.WithPrefix("rid="+httpx.RequestIDFromContext(r)).Printf("invalid input account=%s", req.Account)
httpx.BadRequest(w, r, "invalid account or password")
case service.ErrAccountExists: case service.ErrAccountExists:
httpx.Conflict(w, "account exists") logger.WithPrefix("rid="+httpx.RequestIDFromContext(r)).Printf("account exists account=%s", req.Account)
httpx.Conflict(w, r, "account exists")
default: default:
httpx.InternalError(w) logger.WithPrefix("rid="+httpx.RequestIDFromContext(r)).Printf("internal error account=%s", req.Account)
httpx.InternalError(w, r)
} }
return return
} }
httpx.Created(w, map[string]string{"user_id": userID, "token": token}) logger.WithPrefix("rid="+httpx.RequestIDFromContext(r)).Printf("register success user=%s", userID)
httpx.Created(w, r, map[string]string{"user_id": userID, "token": token})
} }
func (h *Handler) Login(w http.ResponseWriter, r *http.Request) { func (h *Handler) Login(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost { if r.Method != http.MethodPost {
httpx.MethodNotAllowed(w, string(codes.MethodNotAllowed)) logger.WithPrefix("rid="+httpx.RequestIDFromContext(r)).Printf("method not allowed path=%s", r.URL.Path)
httpx.MethodNotAllowed(w, r, string(codes.MethodNotAllowed))
return return
} }
var req model.LoginReq var req model.LoginReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil { if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
httpx.BadRequest(w, "invalid json") logger.WithPrefix("rid="+httpx.RequestIDFromContext(r)).Printf("invalid json path=%s", r.URL.Path)
httpx.BadRequest(w, r, "invalid json")
return return
} }
userID, token, err := h.S.Login(req.Account, req.Password) userID, token, err := h.S.Login(req.Account, req.Password)
if err != nil { if err != nil {
switch err { switch err {
case service.ErrInvalidInput: case service.ErrInvalidInput:
httpx.BadRequest(w, "invalid account or password") logger.WithPrefix("rid="+httpx.RequestIDFromContext(r)).Printf("invalid input account=%s", req.Account)
httpx.BadRequest(w, r, "invalid account or password")
case service.ErrUnauthorized: case service.ErrUnauthorized:
httpx.Unauthorized(w, "unauthorized") logger.WithPrefix("rid="+httpx.RequestIDFromContext(r)).Printf("unauthorized account=%s", req.Account)
httpx.Unauthorized(w, r, "unauthorized")
default: default:
httpx.InternalError(w) logger.WithPrefix("rid="+httpx.RequestIDFromContext(r)).Printf("internal error account=%s", req.Account)
httpx.InternalError(w, r)
} }
return return
} }
httpx.OK(w, map[string]string{"user_id": userID, "token": token}) logger.WithPrefix("rid="+httpx.RequestIDFromContext(r)).Printf("login success user=%s", userID)
httpx.OK(w, r, map[string]string{"user_id": userID, "token": token})
} }
func (h *Handler) Healthz(w http.ResponseWriter, r *http.Request) { func (h *Handler) Healthz(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost { if r.Method != http.MethodPost {
httpx.MethodNotAllowed(w, string(codes.MethodNotAllowed)) logger.WithPrefix("rid="+httpx.RequestIDFromContext(r)).Printf("method not allowed path=%s", r.URL.Path)
httpx.MethodNotAllowed(w, r, string(codes.MethodNotAllowed))
return return
} }
httpx.OK(w, nil) logger.WithPrefix("rid="+httpx.RequestIDFromContext(r)).Printf("healthz ok")
httpx.OK(w, r, nil)
} }
func (h *Handler) Version(w http.ResponseWriter, r *http.Request) { func (h *Handler) Version(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost { if r.Method != http.MethodPost {
httpx.MethodNotAllowed(w, string(codes.MethodNotAllowed)) logger.WithPrefix("rid="+httpx.RequestIDFromContext(r)).Printf("method not allowed path=%s", r.URL.Path)
httpx.MethodNotAllowed(w, r, string(codes.MethodNotAllowed))
return return
} }
httpx.OK(w, map[string]string{"version": "user-service v0.1.0"}) logger.WithPrefix("rid="+httpx.RequestIDFromContext(r)).Printf("version ok")
httpx.OK(w, r, map[string]string{"version": "user-service v0.1.0"})
} }
func (h *Handler) Root(w http.ResponseWriter, r *http.Request) { func (h *Handler) Root(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost { if r.Method != http.MethodPost {
httpx.MethodNotAllowed(w, string(codes.MethodNotAllowed)) logger.WithPrefix("rid="+httpx.RequestIDFromContext(r)).Printf("method not allowed path=%s", r.URL.Path)
httpx.MethodNotAllowed(w, r, string(codes.MethodNotAllowed))
return return
} }
httpx.OK(w, map[string]string{"service": "user", "user_id": httpx.UserID(r)}) logger.WithPrefix("rid="+httpx.RequestIDFromContext(r)).Printf("root ok user=%s", httpx.UserID(r))
httpx.OK(w, r, map[string]string{"service": "user", "user_id": httpx.UserID(r)})
} }