1 Star 0 Fork 0

cruller/gummy

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
gummy.go 2.51 KB
一键复制 编辑 原始数据 按行查看 历史
= 提交于 2024-01-09 10:46 . 初始化仓库
package gummy
import (
"net/http"
"net/url"
"sync"
)
type Gummy struct {
ctxs map[string]*Context
cMx sync.Mutex
headers http.Header
proxy func(*http.Request) (*url.URL, error)
}
func NewGummy() *Gummy {
g := new(Gummy)
g.ctxs = make(map[string]*Context, 8)
g.headers = make(http.Header, 8)
return g
}
func (g *Gummy) GetContext(host string) *Context {
g.cMx.Lock()
var (
ctx *Context
dup bool
)
defer g.cMx.Unlock()
if ctx, dup = g.ctxs[host]; dup {
return ctx
}
ctx = newContext()
g.ctxs[host] = ctx
ctx.SetProxyCall(g.proxy)
ctx.headers = mergeHeaders(ctx.headers, g.headers)
return ctx
}
func (g *Gummy) getContextByURL(rawURL string) (*Context, error) {
u, err := ParseURL(rawURL)
if nil != err {
return nil, err
}
ctx := g.GetContext(u.Host)
return ctx, nil
}
func (g *Gummy) Get(rawURL string, parames ...interface{}) *Response {
return g.RequestURL("GET", rawURL, parames...)
}
func (g *Gummy) Post(rawURL string, parames ...interface{}) *Response {
return g.requestJSON("POST", rawURL, parames...)
}
func (g *Gummy) Put(rawURL string, parames ...interface{}) *Response {
return g.requestJSON("PUT", rawURL, parames...)
}
func (g *Gummy) Delete(rawURL string, parames ...interface{}) *Response {
return g.RequestURL("DELETE", rawURL, parames...)
}
func (g *Gummy) Request(method, rawURL string, parames ...interface{}) *Response {
ctx, err := g.getContextByURL(rawURL)
if nil != err {
return pkgResponse(ctx, nil, err)
}
return ctx.request(method, rawURL, ctx.GetHeaders(), parames...)
}
func (g *Gummy) RequestURL(methon, rawURL string, parames ...interface{}) *Response {
return g.Request(methon, pkgGetURLParames(rawURL, parames...))
}
func (g *Gummy) requestJSON(methon, rawURL string, parames ...interface{}) *Response {
return g.requestAssingContentType(methon, rawURL, "application/json", parames...)
}
func (g *Gummy) requestAssingContentType(method, rawURL, contentType string, parames ...interface{}) *Response {
ctx, err := g.getContextByURL(rawURL)
if nil != err {
return pkgResponse(ctx, nil, err)
}
headers := ctx.GetHeaders()
headers["Content-Type"] = []string{contentType}
return ctx.request(method, rawURL, headers, parames...)
}
func (g *Gummy) SetHeader(key, val string) {
g.headers.Set(key, val)
for _, ctx := range g.ctxs {
if _, dup := ctx.headers[key]; dup {
continue
}
ctx.headers.Set(key, val)
}
}
func (g *Gummy) SetProxy(rawURL string) error {
u, err := url.Parse(rawURL)
if nil != err {
return err
}
g.proxy = http.ProxyURL(u)
return nil
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/cruller/gummy.git
git@gitee.com:cruller/gummy.git
cruller
gummy
gummy
main

搜索帮助