chores: refactor struct and structure project

This commit is contained in:
ericprd
2025-03-05 21:21:44 +08:00
parent 13a8481f22
commit 567e0e32ca
103 changed files with 1125 additions and 731 deletions
+4 -2
View File
@@ -14,8 +14,10 @@ func (e ErrorCode) Error() string {
var (
// 4xx
ErrBadRequest = &ErrorCode{Code: "BAD_REQUEST", Message: "BAD_REQUEST", HttpCode: http.StatusBadRequest}
ErrDBRequest = &ErrorCode{Code: "BAD_DB_REQUEST", Message: "DB_ERROR", HttpCode: http.StatusBadRequest}
ErrBadRequest = &ErrorCode{Code: "BAD_REQUEST", Message: "BAD_REQUEST", HttpCode: http.StatusBadRequest}
ErrUnauthorized = &ErrorCode{Code: "UNAUTHORIZED", Message: "UNAUTHORIZED", HttpCode: http.StatusUnauthorized}
ErrDBRequest = &ErrorCode{Code: "BAD_DB_REQUEST", Message: "DB_ERROR", HttpCode: http.StatusBadRequest}
ErrExpiryToken = &ErrorCode{Code: "EXPIRED_TOKEN", Message: "EXPIRED_TOKEN", HttpCode: http.StatusUnauthorized}
// 5xx
ErrMarshal = &ErrorCode{Code: "FAILED_MARSHAL", Message: "FAILED_MARSHAL_BODY", HttpCode: http.StatusInternalServerError}
@@ -0,0 +1,23 @@
package response
import (
"context"
"encoding/json"
"net/http"
)
func RespondJsonErrorWithCode(ctx context.Context, w http.ResponseWriter,
err error, code string, statusCode int, message string) {
setDefaultHeaders(ctx, w.Header())
w.WriteHeader(statusCode)
b, _ := json.Marshal(ErrorResponse{
Error: ErrorResponseData{
Code: code,
Message: message,
},
})
w.Write(b)
}
@@ -0,0 +1,23 @@
package response
import (
"errors"
"net/http"
)
func RespondWithError(w http.ResponseWriter, r *http.Request, err error, msg string) {
if err != nil {
code := ErrUnauthorized.Code
status := http.StatusUnauthorized
if errors.Is(err, ErrExpiryToken) {
code = ErrExpiryToken.Code
status = ErrExpiryToken.HttpCode
}
RespondJsonErrorWithCode(r.Context(), w, err, code, status, msg)
} else {
RespondJsonErrorWithCode(r.Context(), w, nil,
ErrUnauthorized.Code, http.StatusUnauthorized, msg)
}
}