gapi

package module
v0.0.0-...-85acac4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 15, 2022 License: MIT Imports: 18 Imported by: 0

README

Gapi

一个动态插件化可任意扩展的 Golang 通用API框架

目录

上手指南

目前只有pixiv和城市通(鹤山在线招聘)的一部分API接口, 下一个是nhentai的API接口, 如果需要其他接口可以提issue或者自己添加....不需要公开也能调用(详情: 自定义接口)

Pixiv一百行代码的一步到位演示文件:Demo
简单的使用方法:
p, e := gapi.New(pixiv.URL, &gapi.Options{
	// 国内特供代理设置 例如: socks5://127.0.0.1:7891
	// 如果有帐号密码需要使用BasicAuth, 例如: socks5://admin:admin@127.0.0.1:7891
	ProxyURL: "socks5://127.0.0.1:7891",
	// 超时时间 不传默认为15秒
	Timeout: 15 * time.Second,
})
if e != nil {
	logger.Fatal("创建Gapi客户端失败: %s", e.Error())
}

// 设置api定制全局header
p.SetGHeader(pixiv.GlobalHeader)

resp, e := p.Do(pixiv.CookieLogin(os.Getenv("PIXIV_PHPSESSID")))
if e != nil {
	logger.Fatal("登录失败: %s", e.Error())
}
logger.Info("登录成功: %v", string(resp.Raw()))
自定义API:

完整测试文件:Api

api.New("GET", fmt.Sprintf("/ajax/illust/%d/pages", 1)).
SetHeader("Accept", "application/json; charset=utf-8").
SetValue("lang", "en").
// RespHijack 拦截响应
SetRespHijack(func(resp *http.Response, respBody func(b []byte) []byte) error {
	logger.Info("原始响应状态: %s", resp.Status)
	respBody([]byte("Hijacked"))
	return nil
})

使用到的框架

版权说明

该项目签署了MIT 授权许可,详情请参阅 LICENSE.txt

Documentation

Index

Constants

View Source
const (
	HeaderAccept                        = "Accept"
	HeaderAcceptCharset                 = "Accept-Charset"
	HeaderAcceptEncoding                = "Accept-Encoding"
	HeaderAcceptLanguage                = "Accept-Language"
	HeaderAuthorization                 = "Authorization"
	HeaderCacheControl                  = "Cache-Control"
	HeaderContentLength                 = "Content-Length"
	HeaderContentMD5                    = "Content-MD5"
	HeaderContentType                   = "Content-Type"
	HeaderDoNotTrack                    = "DNT"
	HeaderIfMatch                       = "If-Match"
	HeaderIfModifiedSince               = "If-Modified-Since"
	HeaderIfNoneMatch                   = "If-None-Match"
	HeaderIfRange                       = "If-Range"
	HeaderIfUnmodifiedSince             = "If-Unmodified-Since"
	HeaderMaxForwards                   = "Max-Forwards"
	HeaderProxyAuthorization            = "Proxy-Authorization"
	HeaderPragma                        = "Pragma"
	HeaderRange                         = "Range"
	HeaderReferer                       = "Referer"
	HeaderUserAgent                     = "User-Agent"
	HeaderTE                            = "TE"
	HeaderVia                           = "Via"
	HeaderWarning                       = "Warning"
	HeaderCookie                        = "Cookie"
	HeaderOrigin                        = "Origin"
	HeaderAcceptDatetime                = "Accept-Datetime"
	HeaderXRequestedWith                = "X-Requested-With"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAcceptPatch                   = "Accept-Patch"
	HeaderAcceptRanges                  = "Accept-Ranges"
	HeaderAllow                         = "Allow"
	HeaderContentEncoding               = "Content-Encoding"
	HeaderContentLanguage               = "Content-Language"
	HeaderContentLocation               = "Content-Location"
	HeaderContentDisposition            = "Content-Disposition"
	HeaderContentRange                  = "Content-Range"
	HeaderETag                          = "ETag"
	HeaderExpires                       = "Expires"
	HeaderLastModified                  = "Last-Modified"
	HeaderLink                          = "Link"
	HeaderLocation                      = "Location"
	HeaderP3P                           = "P3P"
	HeaderProxyAuthenticate             = "Proxy-Authenticate"
	HeaderRefresh                       = "Refresh"
	HeaderRetryAfter                    = "Retry-After"
	HeaderServer                        = "Server"
	HeaderSetCookie                     = "Set-Cookie"
	HeaderStrictTransportSecurity       = "Strict-Transport-Security"
	HeaderTransferEncoding              = "Transfer-Encoding"
	HeaderUpgrade                       = "Upgrade"
	HeaderVary                          = "Vary"
	HeaderWWWAuthenticate               = "WWW-Authenticate"

	// Non-Standard
	HeaderXFrameOptions          = "X-Frame-Options"
	HeaderXXSSProtection         = "X-XSS-Protection"
	HeaderContentSecurityPolicy  = "Content-Security-Policy"
	HeaderXContentSecurityPolicy = "X-Content-Security-Policy"
	HeaderXWebKitCSP             = "X-WebKit-CSP"
	HeaderXContentTypeOptions    = "X-Content-Type-Options"
	HeaderXPoweredBy             = "X-Powered-By"
	HeaderXUACompatible          = "X-UA-Compatible"
	HeaderXForwardedProto        = "X-Forwarded-Proto"
	HeaderXHTTPMethodOverride    = "X-HTTP-Method-Override"
	HeaderXForwardedFor          = "X-Forwarded-For"
	HeaderXRealIP                = "X-Real-IP"
	HeaderXCSRFToken             = "X-CSRF-Token"
	HeaderXRatelimitLimit        = "X-Ratelimit-Limit"
	HeaderXRatelimitRemaining    = "X-Ratelimit-Remaining"
	HeaderXRatelimitReset        = "X-Ratelimit-Reset"
	HeaderXFronURLEncoded        = "application/x-www-form-urlencoded"

	// User-Agent
	DefaultUserAgent          = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"
	IDefaultosDeviceUserAgent = "" /* 137-byte string literal not displayed */
)

HTTP headers

Variables

This section is empty.

Functions

This section is empty.

Types

type Gapi

type Gapi struct {
	// contains filtered or unexported fields
}

Gapi 客户端

func New

func New(siteURL string, opts *Options) (*Gapi, error)

New 创建一个Gapi客户端 可以通过设置选项来设置客户端的一些选项

func (*Gapi) Cache

func (p *Gapi) Cache() *cache.Cache

func (*Gapi) ClearCookies

func (p *Gapi) ClearCookies()

清除 cookie 将cookiejar中的所有cookie清除 当设置了PHPSESSID时, 可以使用这个方法来清除

func (*Gapi) Client

func (p *Gapi) Client() *http.Client

func (*Gapi) Do

func (p *Gapi) Do(api *GapiApi) (presp *GapiResponse, e error)

请求Gapi接口 (接口需通过api包里面的方法生成)

func (*Gapi) EndpointPATH

func (p *Gapi) EndpointPATH(path string, values url.Values) *url.URL

生成URL 提供Gapi站点的path和参数返回完整的URL

func (*Gapi) EndpointURL

func (p *Gapi) EndpointURL(urlString string, values url.Values) (*url.URL, error)

生成URL 提供任意的url和参数返回完整的URL

func (*Gapi) GetGHeader

func (p *Gapi) GetGHeader() http.Header

func (*Gapi) GetURL

func (p *Gapi) GetURL() *url.URL

func (*Gapi) Request

func (p *Gapi) Request(ctx context.Context, method, url string, body io.Reader, hijack func(c *http.Client, req *http.Request) error) (*http.Response, error)

创建一个新的http.Client 并且有一个ref可以设置自定义选项然后通过client.Do()来发送请求 将返回原始的http.Response

func (*Gapi) SetGHeader

func (p *Gapi) SetGHeader(m http.Header)

func (*Gapi) SetOptions

func (p *Gapi) SetOptions(opts *Options) error

func (*Gapi) Timeout

func (p *Gapi) Timeout() time.Duration

type GapiApi

type GapiApi struct {
	Method     string
	URL        string
	Headers    http.Header
	Values     url.Values
	Body       []byte
	Error      error
	Hijack     func(p *Gapi, req *http.Request) error
	RespHijack func(resp *GapiResponse, setBody func(b []byte)) error
}

Gapi 接口

func NewAPI

func NewAPI(method string, urlString string) *GapiApi

新建Gapi接口

func (*GapiApi) AddHeader

func (a *GapiApi) AddHeader(key string, value string) *GapiApi

Headers 添加Header

func (*GapiApi) AddValue

func (a *GapiApi) AddValue(key string, value string) *GapiApi

Values (URL Query) 添加Query

func (*GapiApi) DelHeader

func (a *GapiApi) DelHeader(key string)

Headers 删除Header

func (*GapiApi) DelValue

func (a *GapiApi) DelValue(key string)

Values (URL Query) 删除Query

func (*GapiApi) GetBody

func (a *GapiApi) GetBody() []byte

Body 获取请求内容

func (*GapiApi) GetError

func (a *GapiApi) GetError() error

ERROR 获取错误

func (*GapiApi) GetHeader

func (a *GapiApi) GetHeader(key string) string

Headers 获取Header

func (*GapiApi) GetHeaders

func (a *GapiApi) GetHeaders(key string) []string

Headers 获取Headers

func (*GapiApi) GetValue

func (a *GapiApi) GetValue(key string) string

Values (URL Query) 获取Query

func (*GapiApi) HasValue

func (a *GapiApi) HasValue(key string) bool

Values (URL Query) 是否存在Query

func (*GapiApi) SetBody

func (a *GapiApi) SetBody(body []byte) *GapiApi

Body 设置请求内容

func (*GapiApi) SetError

func (a *GapiApi) SetError(e error) *GapiApi

ERROR 抛出错误

func (*GapiApi) SetHeader

func (a *GapiApi) SetHeader(key string, value string) *GapiApi

Headers 设置Header

func (*GapiApi) SetHeaders

func (a *GapiApi) SetHeaders(value map[string]string) *GapiApi

Headers 设置Headers

func (*GapiApi) SetHijack

func (a *GapiApi) SetHijack(hijack func(p *Gapi, req *http.Request) error) *GapiApi

设置请求前的Hijack

func (*GapiApi) SetRespHijack

func (a *GapiApi) SetRespHijack(hijack func(resp *GapiResponse, setBody func(body []byte)) error) *GapiApi

设置请求后的Hijack

func (*GapiApi) SetValue

func (a *GapiApi) SetValue(key string, value string) *GapiApi

Values (URL Query) 设置Query

func (*GapiApi) SetValues

func (a *GapiApi) SetValues(values map[string]string) *GapiApi

Values (URL Query) 设置Querys

type GapiResponse

type GapiResponse struct {
	*http.Response
	// contains filtered or unexported fields
}

Gapi接口返回

func (*GapiResponse) Content

func (r *GapiResponse) Content() ([]byte, error)

获取响应内容 会自动解压缩

func (*GapiResponse) GJSON

func (r *GapiResponse) GJSON() (*gjson.Result, error)

获取JSON响应内容 可以传指针类型的接收者

func (*GapiResponse) Gapi

func (r *GapiResponse) Gapi() *Gapi

func (*GapiResponse) JSON

func (r *GapiResponse) JSON(v ...interface{}) (interface{}, error)

获取JSON响应内容 可以传指针类型的接收者

func (*GapiResponse) OK

func (r *GapiResponse) OK() bool

判断响应是否成功 其实就是判断响应状态码是否在100~399之间

func (*GapiResponse) Raw

func (r *GapiResponse) Raw() []byte

返回原始的响应内容 可以多次调用

func (*GapiResponse) Reason

func (r *GapiResponse) Reason() string

获取相应代码的描述

func (*GapiResponse) Text

func (r *GapiResponse) Text() (string, error)

获取文字响应内容

func (*GapiResponse) URL

func (r *GapiResponse) URL() (*url.URL, error)

获取最终请求的URL

type Options

type Options struct {
	ProxyURL string
	Timeout  time.Duration
}

创建客户端选项

Directories

Path Synopsis
apis
example
api

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL