refactor(http): simplify HTTPBaseResponse options by removing interface and using functional options directly

This commit is contained in:
keven1024
2026-05-23 21:28:51 +08:00
parent 9a9418c564
commit 958ca799da

View File

@@ -6,40 +6,36 @@ import (
"github.com/labstack/echo/v5"
)
type Option interface {
applyTo(*HTTPBaseResponse)
}
type HTTPBaseResponse struct {
code int
message string
data map[string]any
}
type HTTPBaseResponseProps func(props *HTTPBaseResponse) error
type HTTPBaseResponseProps func(props *HTTPBaseResponse)
type WithCode int
func (o WithCode) applyTo(props *HTTPBaseResponse) {
props.code = int(o)
func WithCode(data int) HTTPBaseResponseProps {
return func(props *HTTPBaseResponse) {
props.code = data
}
}
type WithMessage string
func (o WithMessage) applyTo(props *HTTPBaseResponse) {
props.message = string(o)
func WithMessage(data string) HTTPBaseResponseProps {
return func(props *HTTPBaseResponse) {
props.message = data
}
}
type WithData map[string]any
func (o WithData) applyTo(props *HTTPBaseResponse) {
props.data = o
func WithData(data map[string]any) HTTPBaseResponseProps {
return func(props *HTTPBaseResponse) {
props.data = data
}
}
func HTTPBaseHandler(c *echo.Context, options ...Option) error {
func HTTPBaseHandler(c *echo.Context, options ...HTTPBaseResponseProps) error {
props := HTTPBaseResponse{code: http.StatusOK, message: "success", data: map[string]any{}}
for _, option := range options {
option.applyTo(&props)
option(&props)
}
return c.JSON(props.code, map[string]any{
@@ -50,9 +46,11 @@ func HTTPBaseHandler(c *echo.Context, options ...Option) error {
}
func HTTPSuccessHandler(c *echo.Context, data map[string]any, options ...HTTPBaseResponseProps) error {
return HTTPBaseHandler(c, WithData(data))
options = append([]HTTPBaseResponseProps{WithData(data)}, options...)
return HTTPBaseHandler(c, options...)
}
func HTTPErrorHandler(c *echo.Context, err error, options ...HTTPBaseResponseProps) error {
return HTTPBaseHandler(c, WithMessage(err.Error()), WithCode(http.StatusBadRequest))
options = append([]HTTPBaseResponseProps{WithMessage(err.Error()), WithCode(http.StatusBadRequest)}, options...)
return HTTPBaseHandler(c, options...)
}