初始版本,工具基础类

This commit is contained in:
2025-11-30 13:02:34 +08:00
commit ea4e2e305d
37 changed files with 7480 additions and 0 deletions

207
http/request.go Normal file
View File

@@ -0,0 +1,207 @@
package http
import (
"context"
"encoding/json"
"io"
"net/http"
"strconv"
"github.com/go-common/middleware"
)
// ParseJSON 解析JSON请求体
// r: HTTP请求
// v: 目标结构体指针
func ParseJSON(r *http.Request, v interface{}) error {
body, err := io.ReadAll(r.Body)
if err != nil {
return err
}
defer r.Body.Close()
if len(body) == 0 {
return nil
}
return json.Unmarshal(body, v)
}
// GetQuery 获取查询参数
// r: HTTP请求
// key: 参数名
// defaultValue: 默认值
func GetQuery(r *http.Request, key, defaultValue string) string {
value := r.URL.Query().Get(key)
if value == "" {
return defaultValue
}
return value
}
// GetQueryInt 获取整数查询参数
// r: HTTP请求
// key: 参数名
// defaultValue: 默认值
func GetQueryInt(r *http.Request, key string, defaultValue int) int {
value := r.URL.Query().Get(key)
if value == "" {
return defaultValue
}
intValue, err := strconv.Atoi(value)
if err != nil {
return defaultValue
}
return intValue
}
// GetQueryInt64 获取int64查询参数
func GetQueryInt64(r *http.Request, key string, defaultValue int64) int64 {
value := r.URL.Query().Get(key)
if value == "" {
return defaultValue
}
intValue, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return defaultValue
}
return intValue
}
// GetQueryBool 获取布尔查询参数
func GetQueryBool(r *http.Request, key string, defaultValue bool) bool {
value := r.URL.Query().Get(key)
if value == "" {
return defaultValue
}
boolValue, err := strconv.ParseBool(value)
if err != nil {
return defaultValue
}
return boolValue
}
// GetQueryFloat64 获取float64查询参数
func GetQueryFloat64(r *http.Request, key string, defaultValue float64) float64 {
value := r.URL.Query().Get(key)
if value == "" {
return defaultValue
}
floatValue, err := strconv.ParseFloat(value, 64)
if err != nil {
return defaultValue
}
return floatValue
}
// GetFormValue 获取表单值
func GetFormValue(r *http.Request, key, defaultValue string) string {
value := r.FormValue(key)
if value == "" {
return defaultValue
}
return value
}
// GetFormInt 获取表单整数
func GetFormInt(r *http.Request, key string, defaultValue int) int {
value := r.FormValue(key)
if value == "" {
return defaultValue
}
intValue, err := strconv.Atoi(value)
if err != nil {
return defaultValue
}
return intValue
}
// GetFormInt64 获取表单int64
func GetFormInt64(r *http.Request, key string, defaultValue int64) int64 {
value := r.FormValue(key)
if value == "" {
return defaultValue
}
intValue, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return defaultValue
}
return intValue
}
// GetFormBool 获取表单布尔值
func GetFormBool(r *http.Request, key string, defaultValue bool) bool {
value := r.FormValue(key)
if value == "" {
return defaultValue
}
boolValue, err := strconv.ParseBool(value)
if err != nil {
return defaultValue
}
return boolValue
}
// GetHeader 获取请求头
func GetHeader(r *http.Request, key, defaultValue string) string {
value := r.Header.Get(key)
if value == "" {
return defaultValue
}
return value
}
// GetPaginationParams 获取分页参数
// 返回 page, pageSize
// 默认 page=1, pageSize=10
func GetPaginationParams(r *http.Request) (page, pageSize int) {
page = GetQueryInt(r, "page", 1)
pageSize = GetQueryInt(r, "pageSize", 10)
// 参数校验
if page < 1 {
page = 1
}
if pageSize < 1 {
pageSize = 10
}
if pageSize > 1000 {
pageSize = 1000 // 限制最大页面大小
}
return page, pageSize
}
// GetOffset 根据页码和每页大小计算偏移量
func GetOffset(page, pageSize int) int {
if page < 1 {
page = 1
}
return (page - 1) * pageSize
}
// GetTimezone 从请求的context中获取时区
// 如果使用了middleware.Timezone中间件可以从context中获取时区信息
// 如果未设置,返回默认时区 AsiaShanghai
func GetTimezone(r *http.Request) string {
return middleware.GetTimezoneFromContext(r.Context())
}
// GetTimezoneFromContext 从context中获取时区
func GetTimezoneFromContext(ctx context.Context) string {
return middleware.GetTimezoneFromContext(ctx)
}

138
http/response.go Normal file
View File

@@ -0,0 +1,138 @@
package http
import (
"encoding/json"
"net/http"
"time"
)
// Response 标准响应结构
type Response struct {
Code int `json:"code"` // 业务状态码0表示成功
Message string `json:"message"` // 响应消息
Timestamp int64 `json:"timestamp"` // 时间戳
Data interface{} `json:"data"` // 响应数据
}
// PageResponse 分页响应结构
type PageResponse struct {
Code int `json:"code"`
Message string `json:"message"`
Timestamp int64 `json:"timestamp"`
Data *PageData `json:"data"`
}
// PageData 分页数据
type PageData struct {
List interface{} `json:"list"` // 数据列表
Total int64 `json:"total"` // 总记录数
Page int `json:"page"` // 当前页码
PageSize int `json:"pageSize"` // 每页大小
}
// Success 成功响应
// data: 响应数据可以为nil
func Success(w http.ResponseWriter, data interface{}) {
WriteJSON(w, http.StatusOK, 0, "success", data)
}
// SuccessWithMessage 带消息的成功响应
func SuccessWithMessage(w http.ResponseWriter, message string, data interface{}) {
WriteJSON(w, http.StatusOK, 0, message, data)
}
// Error 错误响应
// code: 业务错误码非0表示业务错误
// message: 错误消息
func Error(w http.ResponseWriter, code int, message string) {
WriteJSON(w, http.StatusOK, code, message, nil)
}
// SystemError 系统错误响应返回HTTP 500
// message: 错误消息
func SystemError(w http.ResponseWriter, message string) {
WriteJSON(w, http.StatusInternalServerError, 500, message, nil)
}
// BadRequest 请求错误响应HTTP 400
func BadRequest(w http.ResponseWriter, message string) {
WriteJSON(w, http.StatusBadRequest, 400, message, nil)
}
// Unauthorized 未授权响应HTTP 401
func Unauthorized(w http.ResponseWriter, message string) {
WriteJSON(w, http.StatusUnauthorized, 401, message, nil)
}
// Forbidden 禁止访问响应HTTP 403
func Forbidden(w http.ResponseWriter, message string) {
WriteJSON(w, http.StatusForbidden, 403, message, nil)
}
// NotFound 未找到响应HTTP 404
func NotFound(w http.ResponseWriter, message string) {
WriteJSON(w, http.StatusNotFound, 404, message, nil)
}
// WriteJSON 写入JSON响应
// httpCode: HTTP状态码200表示正常500表示系统错误等
// code: 业务状态码0表示成功非0表示业务错误
// message: 响应消息
// data: 响应数据
func WriteJSON(w http.ResponseWriter, httpCode, code int, message string, data interface{}) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(httpCode)
response := Response{
Code: code,
Message: message,
Timestamp: time.Now().Unix(),
Data: data,
}
json.NewEncoder(w).Encode(response)
}
// SuccessPage 分页成功响应
// list: 数据列表
// total: 总记录数
// page: 当前页码
// pageSize: 每页大小
func SuccessPage(w http.ResponseWriter, list interface{}, total int64, page, pageSize int) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
response := PageResponse{
Code: 0,
Message: "success",
Timestamp: time.Now().Unix(),
Data: &PageData{
List: list,
Total: total,
Page: page,
PageSize: pageSize,
},
}
json.NewEncoder(w).Encode(response)
}
// SuccessPageWithMessage 带消息的分页成功响应
func SuccessPageWithMessage(w http.ResponseWriter, message string, list interface{}, total int64, page, pageSize int) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
response := PageResponse{
Code: 0,
Message: message,
Timestamp: time.Now().Unix(),
Data: &PageData{
List: list,
Total: total,
Page: page,
PageSize: pageSize,
},
}
json.NewEncoder(w).Encode(response)
}