Files
common/http/http.go

78 lines
2.0 KiB
Go
Raw Normal View History

2025-11-25 11:51:16 +08:00
package http
import (
"context"
"errors"
"gitee.com/red-future---jilin-g/common/utils"
"github.com/gogf/gf/contrib/registry/consul/v2"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/gclient"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/net/gsel"
"github.com/gogf/gf/v2/net/gsvc"
"github.com/gogf/gf/v2/os/glog"
"github.com/gogf/gf/v2/util/gconv"
"net/http"
)
type ResponseEmpty struct {
}
const PageSize = 20
type Page struct {
PageNum int `p:"pageNum"` //当前页码
PageSize int `p:"pageSize"` //每页数
Total int //总页数
}
func getHttpClient(ctx context.Context) (client *gclient.Client, err error) {
consulCfg, _ := g.Cfg().Get(context.Background(), "consul.address")
consulAddr := consulCfg.String()
registry, err := consul.New(consul.WithAddress(consulAddr))
if err != nil {
return
}
gsvc.SetRegistry(registry)
gsel.SetBuilder(gsel.NewBuilderRoundRobin())
client = g.Client()
client.SetHeader("Authorization", g.RequestFromCtx(ctx).GetHeader("Authorization"))
client.SetDiscovery(gsvc.GetRegistry())
return
}
func doRequest(ctx context.Context, method string, url string, target any, data ...any) (err error) {
err = utils.ValidStructPtr(target)
if err != nil {
return
}
client, err := getHttpClient(ctx)
if err != nil {
return
}
2025-11-25 13:07:27 +08:00
response, err := client.DoRequest(ctx, method, url, data)
2025-11-25 11:51:16 +08:00
if err != nil {
return
}
defer func() {
if err = response.Close(); err != nil {
glog.Errorf(ctx, `%+v`, err)
}
}()
result := response.ReadAll()
resultStrut := &ghttp.DefaultHandlerResponse{}
if gconv.Struct(result, resultStrut); resultStrut.Code != 200 {
err = errors.New(resultStrut.Message)
} else {
gconv.Struct(resultStrut.Data, target)
}
return
}
func Get(ctx context.Context, url string, target any, data ...any) (err error) {
err = doRequest(ctx, http.MethodGet, url, target, data)
return
}
func Post(ctx context.Context, url string, target any, data ...any) (err error) {
err = doRequest(ctx, http.MethodPost, url, target, data)
return
}