Files
ai-ops/pkg/response/response.go
2026-05-12 17:48:22 +08:00

60 lines
1.3 KiB
Go

package response
import (
"encoding/json"
"net/http"
"github.com/company/ai-ops/pkg/errors"
)
// Response 是统一响应结构
type Response struct {
Code string `json:"code,omitempty"`
Message string `json:"message,omitempty"`
Data any `json:"data,omitempty"`
}
// JSON 返回 JSON 响应
func JSON(w http.ResponseWriter, status int, data any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(data)
}
// Success 返回成功响应
func Success(w http.ResponseWriter, data any) {
JSON(w, http.StatusOK, Response{Data: data})
}
// Error 返回错误响应
func Error(w http.ResponseWriter, err *errors.AppError) {
JSON(w, err.HTTPStatus, Response{
Code: err.Code,
Message: err.Message,
})
}
// Paginated 是分页响应结构
type Paginated struct {
Items any `json:"items"`
Total int `json:"total"`
Page int `json:"page"`
PageSize int `json:"page_size"`
TotalPages int `json:"total_pages"`
}
// PaginatedResponse 返回分页响应
func PaginatedResponse(w http.ResponseWriter, items any, total, page, pageSize int) {
totalPages := total / pageSize
if total%pageSize > 0 {
totalPages++
}
Success(w, Paginated{
Items: items,
Total: total,
Page: page,
PageSize: pageSize,
TotalPages: totalPages,
})
}