forked from mtusi2026/mtusi2026lab3
refactor(app) agent refactoring + a little review
This commit is contained in:
@@ -4,6 +4,7 @@ package common
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/gofiber/fiber/v3/middleware/requestid"
|
||||
@@ -41,10 +42,13 @@ func NewError(code, message, requestID string) APIErrorResponse {
|
||||
}
|
||||
}
|
||||
|
||||
// AppError is the single contract error type. Handlers and the store return it;
|
||||
// the Fiber error handler is the only place that turns it into a response.
|
||||
type AppError struct {
|
||||
Status int
|
||||
Code string
|
||||
Message string
|
||||
Status int
|
||||
Code string
|
||||
Message string
|
||||
Challenge string // WWW-Authenticate value, set for 401 responses
|
||||
}
|
||||
|
||||
func (e *AppError) Error() string {
|
||||
@@ -60,31 +64,37 @@ func NewAppError(status int, code, message string) *AppError {
|
||||
}
|
||||
|
||||
func BadRequest(message string) *AppError {
|
||||
return NewAppError(fiber.StatusBadRequest, ErrorCodeInvalidRequest, message)
|
||||
}
|
||||
|
||||
func Unauthorized(message string) *AppError {
|
||||
return NewAppError(fiber.StatusUnauthorized, ErrorCodeUnauthorized, message)
|
||||
return NewAppError(http.StatusBadRequest, ErrorCodeInvalidRequest, message)
|
||||
}
|
||||
|
||||
func NotFound(message string) *AppError {
|
||||
return NewAppError(fiber.StatusNotFound, ErrorCodeNotFound, message)
|
||||
return NewAppError(http.StatusNotFound, ErrorCodeNotFound, message)
|
||||
}
|
||||
|
||||
func Conflict(message string) *AppError {
|
||||
return NewAppError(fiber.StatusConflict, ErrorCodeConflict, message)
|
||||
return NewAppError(http.StatusConflict, ErrorCodeConflict, message)
|
||||
}
|
||||
|
||||
func UnsupportedMedia(message string) *AppError {
|
||||
return NewAppError(fiber.StatusUnsupportedMediaType, ErrorCodeUnsupportedMedia, message)
|
||||
return NewAppError(http.StatusUnsupportedMediaType, ErrorCodeUnsupportedMedia, message)
|
||||
}
|
||||
|
||||
func Internal() *AppError {
|
||||
return NewAppError(fiber.StatusInternalServerError, ErrorCodeInternal, "Internal server error")
|
||||
return NewAppError(http.StatusInternalServerError, ErrorCodeInternal, "Internal server error")
|
||||
}
|
||||
|
||||
func Unavailable(message string) *AppError {
|
||||
return NewAppError(fiber.StatusServiceUnavailable, ErrorCodeUnavailable, message)
|
||||
return NewAppError(http.StatusServiceUnavailable, ErrorCodeUnavailable, message)
|
||||
}
|
||||
|
||||
// NewChallenge builds the 401 that carries a WWW-Authenticate header.
|
||||
func NewChallenge(challenge, message string) *AppError {
|
||||
return &AppError{
|
||||
Status: http.StatusUnauthorized,
|
||||
Code: ErrorCodeUnauthorized,
|
||||
Message: message,
|
||||
Challenge: challenge,
|
||||
}
|
||||
}
|
||||
|
||||
// IsCode reports whether err is an AppError with the given contract code.
|
||||
@@ -95,21 +105,21 @@ func IsCode(err error, code string) bool {
|
||||
|
||||
func ErrorCodeFromStatus(status int) string {
|
||||
switch status {
|
||||
case fiber.StatusBadRequest:
|
||||
case http.StatusBadRequest:
|
||||
return ErrorCodeInvalidRequest
|
||||
case fiber.StatusUnauthorized:
|
||||
case http.StatusUnauthorized:
|
||||
return ErrorCodeUnauthorized
|
||||
case fiber.StatusNotFound:
|
||||
case http.StatusNotFound:
|
||||
return ErrorCodeNotFound
|
||||
case fiber.StatusConflict:
|
||||
case http.StatusConflict:
|
||||
return ErrorCodeConflict
|
||||
case fiber.StatusRequestEntityTooLarge:
|
||||
case http.StatusRequestEntityTooLarge:
|
||||
return ErrorCodePayloadTooLarge
|
||||
case fiber.StatusUnsupportedMediaType:
|
||||
case http.StatusUnsupportedMediaType:
|
||||
return ErrorCodeUnsupportedMedia
|
||||
case fiber.StatusTooManyRequests:
|
||||
case http.StatusTooManyRequests:
|
||||
return ErrorCodeRateLimited
|
||||
case fiber.StatusServiceUnavailable:
|
||||
case http.StatusServiceUnavailable:
|
||||
return ErrorCodeUnavailable
|
||||
default:
|
||||
return ErrorCodeInternal
|
||||
@@ -126,17 +136,3 @@ func getRequestID(c fiber.Ctx) string {
|
||||
func SendError(c fiber.Ctx, status int, code, message string) error {
|
||||
return c.Status(status).JSON(NewError(code, message, getRequestID(c)))
|
||||
}
|
||||
|
||||
func SendAppError(c fiber.Ctx, err error) error {
|
||||
if appErr, ok := errors.AsType[*AppError](err); ok {
|
||||
return SendError(c, appErr.Status, appErr.Code, appErr.Message)
|
||||
}
|
||||
|
||||
return SendError(c, fiber.StatusInternalServerError,
|
||||
ErrorCodeInternal, "Internal server error")
|
||||
}
|
||||
|
||||
func SendChallenge(c fiber.Ctx, challenge, message string) error {
|
||||
c.Set(fiber.HeaderWWWAuthenticate, challenge)
|
||||
return SendError(c, fiber.StatusUnauthorized, ErrorCodeUnauthorized, message)
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ func TestValidateIdempotencyKey(t *testing.T) {
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got := ValidateIdempotencyKey(test.key) == ""
|
||||
got := ValidateIdempotencyKey(test.key) == nil
|
||||
if got != test.ok {
|
||||
t.Fatalf("ValidateIdempotencyKey(%q) valid = %v, want %v", test.key, got, test.ok)
|
||||
}
|
||||
|
||||
@@ -27,3 +27,13 @@ func SessionToken(c fiber.Ctx) (string, bool) {
|
||||
token, ok := c.Locals(KeySessionToken).(string)
|
||||
return token, ok && token != ""
|
||||
}
|
||||
|
||||
// PathUUID parses a UUID path parameter. A malformed value is a contract
|
||||
// invalid_request, not a lookup failure.
|
||||
func PathUUID(c fiber.Ctx, name string) (uuid.UUID, error) {
|
||||
id, err := uuid.Parse(c.Params(name))
|
||||
if err != nil {
|
||||
return uuid.Nil, BadRequest("invalid " + name + " format")
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ func TestValidatePasswordRange(t *testing.T) {
|
||||
{"😀", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := ValidatePassword(tc.password) == ""; got != tc.valid {
|
||||
if got := ValidatePassword(tc.password) == nil; got != tc.valid {
|
||||
t.Fatalf("ValidatePassword(%q) valid=%v, want %v", tc.password, got, tc.valid)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,71 +22,71 @@ func strLenBetween(s string, min, max int) bool {
|
||||
return n >= min && n <= max
|
||||
}
|
||||
|
||||
func ValidateCreateUser(username, displayName string) string {
|
||||
func ValidateCreateUser(username, displayName string) error {
|
||||
if !usernameRegex.MatchString(username) {
|
||||
return "username must match ^[a-z0-9_]{3,32}$"
|
||||
return BadRequest("username must match ^[a-z0-9_]{3,32}$")
|
||||
}
|
||||
|
||||
if blank(displayName) {
|
||||
return "display_name must not be empty or only whitespace"
|
||||
return BadRequest("display_name must not be empty or only whitespace")
|
||||
}
|
||||
|
||||
if !strLenBetween(displayName, 1, 100) {
|
||||
return "display_name must be between 1 and 100 Unicode code points"
|
||||
return BadRequest("display_name must be between 1 and 100 Unicode code points")
|
||||
}
|
||||
|
||||
return ""
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidatePassword(password string) string {
|
||||
func ValidatePassword(password string) error {
|
||||
if blank(password) {
|
||||
return "password must not be empty or only whitespace"
|
||||
return BadRequest("password must not be empty or only whitespace")
|
||||
}
|
||||
|
||||
if !strLenBetween(password, 12, 128) {
|
||||
return "password must be between 12 and 128 Unicode code points"
|
||||
return BadRequest("password must be between 12 and 128 Unicode code points")
|
||||
}
|
||||
|
||||
return ""
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateChatTitle(title string) string {
|
||||
func ValidateChatTitle(title string) error {
|
||||
if blank(title) {
|
||||
return "title must not be empty or only whitespace"
|
||||
return BadRequest("title must not be empty or only whitespace")
|
||||
}
|
||||
|
||||
if !strLenBetween(title, 1, 100) {
|
||||
return "title must be between 1 and 100 Unicode code points"
|
||||
return BadRequest("title must be between 1 and 100 Unicode code points")
|
||||
}
|
||||
|
||||
return ""
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateMessageText(text string) string {
|
||||
func ValidateMessageText(text string) error {
|
||||
if blank(text) {
|
||||
return "text must not be empty or only whitespace"
|
||||
return BadRequest("text must not be empty or only whitespace")
|
||||
}
|
||||
|
||||
if !strLenBetween(text, 1, 4000) {
|
||||
return "text must be between 1 and 4000 Unicode code points"
|
||||
return BadRequest("text must be between 1 and 4000 Unicode code points")
|
||||
}
|
||||
|
||||
return ""
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateIdempotencyKey(key string) string {
|
||||
func ValidateIdempotencyKey(key string) error {
|
||||
if key == "" {
|
||||
return "Idempotency-Key header is required"
|
||||
return BadRequest("Idempotency-Key header is required")
|
||||
}
|
||||
if !idempotencyKeyRegex.MatchString(key) {
|
||||
return "Idempotency-Key must match ^[A-Za-z0-9._:-]{1,128}$"
|
||||
return BadRequest("Idempotency-Key must match ^[A-Za-z0-9._:-]{1,128}$")
|
||||
}
|
||||
return ""
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateMemberIDs(ids []uuid.UUID, callerID uuid.UUID) string {
|
||||
func ValidateMemberIDs(ids []uuid.UUID, callerID uuid.UUID) error {
|
||||
if len(ids) < 1 || len(ids) > 100 {
|
||||
return "member_ids must contain between 1 and 100 members"
|
||||
return BadRequest("member_ids must contain between 1 and 100 members")
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]bool, len(ids))
|
||||
@@ -94,7 +94,7 @@ func ValidateMemberIDs(ids []uuid.UUID, callerID uuid.UUID) string {
|
||||
|
||||
for _, id := range ids {
|
||||
if seen[id] {
|
||||
return "member_ids must not contain duplicates"
|
||||
return BadRequest("member_ids must not contain duplicates")
|
||||
}
|
||||
|
||||
seen[id] = true
|
||||
@@ -105,8 +105,8 @@ func ValidateMemberIDs(ids []uuid.UUID, callerID uuid.UUID) string {
|
||||
}
|
||||
|
||||
if !callerFound {
|
||||
return "caller must be included in member_ids"
|
||||
return BadRequest("caller must be included in member_ids")
|
||||
}
|
||||
|
||||
return ""
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user