初始化2
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Resp 统一返回结构
|
||||
type Resp struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Data any `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, body any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(body)
|
||||
}
|
||||
|
||||
// Ok 成功
|
||||
func Ok(w http.ResponseWriter, data any) {
|
||||
writeJSON(w, http.StatusOK, Resp{Code: 0, Message: "success", Data: data})
|
||||
}
|
||||
|
||||
// OkCode 成功但自定义 message
|
||||
func OkMessage(w http.ResponseWriter, message string, data any) {
|
||||
writeJSON(w, http.StatusOK, Resp{Code: 0, Message: message, Data: data})
|
||||
}
|
||||
|
||||
// Fail 业务失败(HTTP 200,业务码非0)
|
||||
func Fail(w http.ResponseWriter, code int, message string) {
|
||||
writeJSON(w, http.StatusOK, Resp{Code: code, Message: message})
|
||||
}
|
||||
|
||||
// FailHTTP 直接返回 HTTP 错误
|
||||
func FailHTTP(w http.ResponseWriter, status int, message string) {
|
||||
writeJSON(w, status, Resp{Code: status, Message: message})
|
||||
}
|
||||
|
||||
// BadRequest 参数错误
|
||||
func BadRequest(w http.ResponseWriter, message string) {
|
||||
writeJSON(w, http.StatusBadRequest, Resp{Code: 400, Message: message})
|
||||
}
|
||||
|
||||
func InternalError(w http.ResponseWriter, message string) {
|
||||
writeJSON(w, http.StatusInternalServerError, Resp{Code: 500, Message: message})
|
||||
}
|
||||
|
||||
func Unauthorized(w http.ResponseWriter, message string) {
|
||||
writeJSON(w, http.StatusUnauthorized, Resp{Code: 401, Message: message})
|
||||
}
|
||||
|
||||
// ParseJSON 解析请求体
|
||||
func ParseJSON(r *http.Request, v any) error {
|
||||
dec := json.NewDecoder(r.Body)
|
||||
return dec.Decode(v)
|
||||
}
|
||||
Reference in New Issue
Block a user