package http import ( "net/http" "git.toowon.com/jimmy/go-common/i18n" ) // Handler HTTP 出参处理器(唯一对外出参方式) type Handler struct { w http.ResponseWriter r *http.Request i18n *i18n.I18n pagination *PaginationRequest } // HandlerOption Handler 配置项 type HandlerOption func(*Handler) // WithI18n 注入 i18n func WithI18n(i *i18n.I18n) HandlerOption { return func(h *Handler) { h.i18n = i } } // NewHandler 创建 HTTP 出参处理器 func NewHandler(w http.ResponseWriter, r *http.Request, opts ...HandlerOption) *Handler { h := &Handler{w: w, r: r} for _, opt := range opts { opt(h) } return h } // ParseJSON 解析 JSON 请求体 func (h *Handler) ParseJSON(v interface{}) error { return ParseJSON(h.r, v) } // Pagination 解析并缓存分页参数 func (h *Handler) Pagination() *PaginationRequest { if h.pagination == nil { h.pagination = ParsePaginationRequest(h.r) } return h.pagination } // GetLanguage 从 context 获取语言 func (h *Handler) GetLanguage() string { return GetLanguage(h.r) } // GetTimezone 从 context 获取时区 func (h *Handler) GetTimezone() string { return GetTimezone(h.r) } // Success 成功响应 func (h *Handler) Success(data interface{}) { message := "success" code := 0 if h.i18n != nil { info := h.i18n.GetMessageInfo(h.GetLanguage(), "common.success") if info.Message != "common.success" { message = info.Message code = info.Code } } writeResponse(h.w, code, message, data) } // SuccessPage 分页成功响应 func (h *Handler) SuccessPage(list interface{}, total int64) { p := h.Pagination() pageData := &PageData{ List: list, Total: total, Page: p.GetPage(), PageSize: p.GetPageSize(), } h.Success(pageData) } // Error 失败响应(messageCode 为 i18n 消息码) func (h *Handler) Error(messageCode string, args ...interface{}) { code := 0 message := messageCode if h.i18n != nil { info := h.i18n.GetMessageInfo(h.GetLanguage(), messageCode, args...) code = info.Code message = info.Message } writeResponse(h.w, code, message, nil) }