133 lines
2.2 KiB
Go
133 lines
2.2 KiB
Go
package core
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httputil"
|
|
"net/url"
|
|
"platform/pkg/env"
|
|
"platform/pkg/u"
|
|
"reflect"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
// PageReq 分页请求参数
|
|
type PageReq struct {
|
|
RawPage int `json:"page"`
|
|
RawSize int `json:"size"`
|
|
}
|
|
|
|
func (p *PageReq) GetPage() int {
|
|
if p.RawPage < 1 {
|
|
return 1
|
|
}
|
|
return p.RawPage
|
|
}
|
|
|
|
func (p *PageReq) GetSize() int {
|
|
if p.RawSize < 1 {
|
|
return 10
|
|
}
|
|
if p.RawSize > 100 {
|
|
return 100
|
|
}
|
|
return p.RawSize
|
|
}
|
|
|
|
func (p *PageReq) GetOffset() int {
|
|
return (p.GetPage() - 1) * p.GetSize()
|
|
}
|
|
|
|
func (p *PageReq) GetLimit() int {
|
|
return p.GetSize()
|
|
}
|
|
|
|
// PageResp 分页响应参数
|
|
type PageResp struct {
|
|
Total int `json:"total"`
|
|
Page int `json:"page"`
|
|
Size int `json:"size"`
|
|
List any `json:"list"`
|
|
}
|
|
|
|
// Fetch 发送HTTP请求并返回响应
|
|
func Fetch(req *http.Request) (*http.Response, error) {
|
|
if env.DebugHttpDump {
|
|
str, err := httputil.DumpRequest(req, true)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
fmt.Printf("===== REQUEST ===== %s\n", req.URL)
|
|
fmt.Println(string(str))
|
|
}
|
|
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if env.DebugHttpDump {
|
|
str, err := httputil.DumpResponse(resp, true)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
fmt.Printf("===== RESPONSE ===== %s\n", req.URL)
|
|
fmt.Println(string(str))
|
|
}
|
|
|
|
return resp, nil
|
|
}
|
|
|
|
func Query(in any) url.Values {
|
|
out := url.Values{}
|
|
|
|
if in == nil {
|
|
return out
|
|
}
|
|
|
|
ref := reflect.ValueOf(in)
|
|
if ref.Kind() == reflect.Pointer {
|
|
ref = ref.Elem()
|
|
}
|
|
|
|
if ref.Kind() != reflect.Struct {
|
|
return out
|
|
}
|
|
|
|
for i := 0; i < ref.NumField(); i++ {
|
|
field := ref.Type().Field(i)
|
|
value := ref.Field(i)
|
|
|
|
if field.Type.Kind() == reflect.Pointer {
|
|
if value.IsNil() {
|
|
continue
|
|
}
|
|
value = value.Elem()
|
|
}
|
|
|
|
name := field.Name
|
|
tags := strings.Split(field.Tag.Get("query"), ",")
|
|
if len(tags) > 0 && tags[0] != "" {
|
|
name = tags[0]
|
|
}
|
|
|
|
switch value := value.Interface().(type) {
|
|
case string:
|
|
out.Add(name, url.QueryEscape(value))
|
|
case int:
|
|
out.Add(name, strconv.Itoa(value))
|
|
case bool:
|
|
if tags[1] == "b2i" {
|
|
out.Add(name, u.Ternary(value, "1", "0"))
|
|
} else {
|
|
out.Add(name, strconv.FormatBool(value))
|
|
}
|
|
default:
|
|
out.Add(name, fmt.Sprintf("%v", value))
|
|
}
|
|
}
|
|
|
|
return out
|
|
}
|