代码拉取完成,页面将自动刷新
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
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。