Documentation
¶
Index ¶
- Variables
- func Apply(request *http.Request, options ...Option) (*http.Request, error)
- func New(method, url string, options ...Option) (*http.Request, error)
- func NewDelete(url string, options ...Option) (*http.Request, error)
- func NewGet(url string, options ...Option) (*http.Request, error)
- func NewHead(url string, options ...Option) (*http.Request, error)
- func NewOptions(url string, options ...Option) (*http.Request, error)
- func NewPatch(url string, options ...Option) (*http.Request, error)
- func NewPost(url string, options ...Option) (*http.Request, error)
- func NewPut(url string, options ...Option) (*http.Request, error)
- type Client
- func (c *Client) Call(method string, result any, options ...Option) (*Response, error)
- func (c *Client) CallWithRequest(request *http.Request, result any, options ...Option) (*Response, error)
- func (c *Client) Delete(options ...Option) (*Response, error)
- func (c *Client) Do(method string, options ...Option) (*Response, error)
- func (c *Client) DoWithRequest(request *http.Request, options ...Option) (*Response, error)
- func (c *Client) Get(options ...Option) (*Response, error)
- func (c *Client) GetHTTPClient() *http.Client
- func (c *Client) Head(options ...Option) (*Response, error)
- func (c *Client) Options(options ...Option) (*Response, error)
- func (c *Client) Patch(options ...Option) (*Response, error)
- func (c *Client) Post(options ...Option) (*Response, error)
- func (c *Client) Put(options ...Option) (*Response, error)
- func (c *Client) SetAfterOptions(afterOptions ...Option) *Client
- func (c *Client) SetHTTPClient(hc *http.Client) *Client
- func (c *Client) SetJSONUnmarshaler(unmarshaler Unmarshaler) *Client
- func (c *Client) SetProxy(proxyURL string) *Client
- func (c *Client) SetTLSClientConfig(config *tls.Config) *Client
- func (c *Client) SetTimeout(timeout time.Duration) *Client
- func (c *Client) SetTransport(transport http.RoundTripper) *Client
- func (c *Client) SetXMLUnmarshaler(unmarshaler Unmarshaler) *Client
- type Config
- type Marshaler
- type Option
- func Accept(accept string) Option
- func AddCookies(cookies ...*http.Cookie) Option
- func AddPath(segments ...string) Option
- func AddQueries(queries stdurl.Values) Option
- func AddQuery(key string, value any) Option
- func AddQueryMap(queryMap map[string]any) Option
- func Authorization(authorization string) Option
- func BasicAuth(username, password string) Option
- func BearerAuth(token string) Option
- func Body(body io.ReadCloser) Option
- func BodyBytes(body []byte) Option
- func BodyForm(body stdurl.Values) Option
- func BodyFormMap(formMap map[string]any) Option
- func BodyJSON(obj any, marshaler ...Marshaler) Option
- func BodyReader(body io.Reader) Option
- func BodyString(body string) Option
- func BodyXML(obj any, marshaler ...Marshaler) Option
- func CacheControl(cacheControl string) Option
- func ContentLength(contentLength int) Option
- func ContentType(contentType string) Option
- func Context(ctx context.Context) Option
- func ContextValue(key, value any) Option
- func Dump(w io.Writer) Option
- func Header(key string, values ...string) Option
- func HeaderMap(headerMap map[string]string) Option
- func Headers(headers http.Header) Option
- func Host(host string) Option
- func Method(method string) Option
- func Path(segments ...string) Option
- func Queries(queries stdurl.Values) Option
- func Query(key string, value any) Option
- func QueryMap(queryMap map[string]any) Option
- func RawURL(url *stdurl.URL) Option
- func Referer(referer string) Option
- func Scheme(scheme string) Option
- func TokenAuth(token string) Option
- func URL(url string) Option
- func User(user *stdurl.Userinfo) Option
- func UserAgent(userAgent string) Option
- func UserPassword(username, password string) Option
- func Username(username string) Option
- type OptionCollection
- type OptionFunc
- type Response
- func Delete(url string, options ...Option) (*Response, error)
- func Do(method, url string, options ...Option) (*Response, error)
- func Get(url string, options ...Option) (*Response, error)
- func Head(url string, options ...Option) (*Response, error)
- func Options(url string, options ...Option) (*Response, error)
- func Patch(url string, options ...Option) (*Response, error)
- func Post(url string, options ...Option) (*Response, error)
- func Put(url string, options ...Option) (*Response, error)
- func (r *Response) Bytes() []byte
- func (r *Response) ContentType() string
- func (r *Response) Cookies() []*http.Cookie
- func (r *Response) GetAllHeadersString() string
- func (r *Response) Header() http.Header
- func (r *Response) IsError() bool
- func (r *Response) IsSuccess() bool
- func (r *Response) JSONUnmarshal(v any) error
- func (r *Response) Proto() string
- func (r *Response) RawBody() io.ReadCloser
- func (r *Response) ReceivedAt() time.Time
- func (r *Response) Size() int64
- func (r *Response) Status() string
- func (r *Response) StatusCode() int
- func (r *Response) String() string
- func (r *Response) Unmarshal(v any) error
- func (r *Response) XMLUnmarshal(v any) error
- type Unmarshaler
Examples ¶
- Accept
- AddCookies
- AddPath
- AddQueries
- AddQuery
- AddQueryMap
- Apply
- Authorization
- BasicAuth
- BearerAuth
- Body
- BodyBytes
- BodyForm
- BodyFormMap
- BodyJSON
- BodyReader
- BodyString
- BodyXML
- CacheControl
- Client.Call
- Client.CallWithRequest
- Client.Do
- Client.DoWithRequest
- ContentLength
- ContentType
- Context
- ContextValue
- Do
- Dump
- Header
- HeaderMap
- Headers
- Host
- Method
- New
- NewClient
- NewDelete
- NewGet
- NewHead
- NewOptions
- NewPatch
- NewPost
- NewPut
- OptionFunc
- Path
- Queries
- Query
- QueryMap
- RawURL
- Referer
- Response
- Scheme
- TokenAuth
- URL
- User
- UserAgent
- UserPassword
- Username
Constants ¶
This section is empty.
Variables ¶
var ( // DefaultConfig 获取默认 HTTP 客户端配置 DefaultConfig = xhttp.DefaultConfig // NewHTTPClient 新建 HTTP 客户端(不传递配置时,将使用默认配置 DefaultConfig) NewHTTPClient = xhttp.NewHTTPClient // DefaultHTTPClient 默认 HTTP 客户端 DefaultHTTPClient = NewHTTPClient() // DefaultClient 默认 HTTP 拓展客户端 DefaultClient = NewClient() )
Functions ¶
func Apply ¶
Apply 将可选参数列表应用于 http 请求中
Example ¶
package main
import (
"context"
"fmt"
"io"
"net/http"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := http.NewRequestWithContext(context.Background(), http.MethodPost, "", nil)
request, _ = xreq.Apply(request,
xreq.URL("https://www.test.com"),
xreq.Path("api", "/students"),
xreq.BearerAuth("abcdefgh"),
xreq.BodyJSON(map[string]string{"name": "SliverYou", "language": "go"}),
)
body, _ := io.ReadAll(request.Body)
fmt.Println(request.Method)
fmt.Println(request.URL)
fmt.Println(string(body))
fmt.Println(request.ContentLength)
fmt.Println(request.Header.Get("Content-Type"))
}
Output: POST https://www.test.com/api/students {"language":"go","name":"SliverYou"} 36 application/json
func New ¶
New 新建 HTTP 请求
Example ¶
package main
import (
"context"
"fmt"
"io"
"net/http"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
ctx := context.TODO()
request, _ := xreq.New(http.MethodPost, "http://www.test.com/api",
xreq.Context(ctx),
xreq.Scheme("https"),
xreq.Host("my.test.com"),
xreq.AddPath("/students"),
xreq.BearerAuth("abcdefgh"),
xreq.BodyJSON(map[string]string{"name": "SliverYou", "language": "go"}),
)
body, _ := io.ReadAll(request.Body)
fmt.Println(request.Method)
fmt.Println(request.URL)
fmt.Println(string(body))
fmt.Println(request.ContentLength)
fmt.Println(request.Header.Get("Content-Type"))
fmt.Println(request.Header.Get("Authorization"))
}
Output: POST https://my.test.com/api/students {"language":"go","name":"SliverYou"} 36 application/json Bearer abcdefgh
func NewDelete ¶
NewDelete 新建 HTTP DELETE 请求
Example ¶
package main
import (
"context"
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
ctx := context.TODO()
request, _ := xreq.NewDelete("https://www.test.com/api",
xreq.Context(ctx),
xreq.AddPath("/file/1"),
xreq.Query("file_type", "1"),
)
fmt.Println(request.Method)
fmt.Println(request.URL)
}
Output: DELETE https://www.test.com/api/file/1?file_type=1
func NewGet ¶
NewGet 新建 HTTP GET 请求
Example ¶
package main
import (
"context"
"fmt"
"net/url"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
ctx := context.TODO()
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.Context(ctx),
xreq.AddPath("files"),
xreq.Queries(url.Values{
"page": {"10"},
"page_size": {"50"},
}),
)
fmt.Println(request.Method)
fmt.Println(request.URL)
}
Output: GET https://www.test.com/api/files?page=10&page_size=50
func NewHead ¶
NewHead 新建 HTTP HEAD 请求
Example ¶
package main
import (
"context"
"fmt"
"net/url"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
ctx := context.TODO()
request, _ := xreq.NewHead("https://www.test.com/api",
xreq.Context(ctx),
xreq.AddPath("files"),
xreq.Queries(url.Values{
"page": {"10"},
"page_size": {"50"},
}),
)
fmt.Println(request.Method)
fmt.Println(request.URL)
}
Output: HEAD https://www.test.com/api/files?page=10&page_size=50
func NewOptions ¶
NewOptions 新建 HTTP OPTIONS 请求
Example ¶
package main
import (
"context"
"fmt"
"io"
"net/http"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
ctx := context.TODO()
request, _ := xreq.NewOptions("https://www.test.com/api",
xreq.Context(ctx),
xreq.AddPath("/students"),
xreq.Headers(http.Header{
"Origin": {"https://my.test.com"},
"Access-Control-Request-Method": {"PUT"},
"Access-Control-Request-Headers": {"Authorization", "Content-Type"},
}),
xreq.BodyJSON(map[string]any{"id": 1, "name": "SliverYou", "language": "go"}),
)
body, _ := io.ReadAll(request.Body)
fmt.Println(request.Method)
fmt.Println(request.URL)
fmt.Println(string(body))
fmt.Println(request.ContentLength)
fmt.Println(request.Header.Get("Content-Type"))
}
Output: OPTIONS https://www.test.com/api/students {"id":1,"language":"go","name":"SliverYou"} 43 application/json
func NewPatch ¶
NewPatch 新建 HTTP PATCH 请求
Example ¶
package main
import (
"context"
"fmt"
"io"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
ctx := context.TODO()
request, _ := xreq.NewPatch("https://www.test.com/api",
xreq.Context(ctx),
xreq.AddPath("/students"),
xreq.BodyJSON(map[string]any{"id": 1, "name": "SliverYou"}),
)
body, _ := io.ReadAll(request.Body)
fmt.Println(request.Method)
fmt.Println(request.URL)
fmt.Println(string(body))
fmt.Println(request.ContentLength)
fmt.Println(request.Header.Get("Content-Type"))
}
Output: PATCH https://www.test.com/api/students {"id":1,"name":"SliverYou"} 27 application/json
func NewPost ¶
NewPost 新建 HTTP POST 请求
Example ¶
package main
import (
"context"
"fmt"
"io"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
ctx := context.TODO()
request, _ := xreq.NewPost("https://www.test.com/api",
xreq.Context(ctx),
xreq.AddPath("/students"),
xreq.BodyJSON(map[string]string{"name": "SliverYou", "language": "go"}),
)
body, _ := io.ReadAll(request.Body)
fmt.Println(request.Method)
fmt.Println(request.URL)
fmt.Println(string(body))
fmt.Println(request.ContentLength)
fmt.Println(request.Header.Get("Content-Type"))
}
Output: POST https://www.test.com/api/students {"language":"go","name":"SliverYou"} 36 application/json
func NewPut ¶
NewPut 新建 HTTP PUT 请求
Example ¶
package main
import (
"context"
"fmt"
"io"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
ctx := context.TODO()
request, _ := xreq.NewPut("https://www.test.com/api",
xreq.Context(ctx),
xreq.AddPath("/students"),
xreq.BodyJSON(map[string]any{"id": 1, "name": "SliverYou", "language": "go"}),
)
body, _ := io.ReadAll(request.Body)
fmt.Println(request.Method)
fmt.Println(request.URL)
fmt.Println(string(body))
fmt.Println(request.ContentLength)
fmt.Println(request.Header.Get("Content-Type"))
}
Output: PUT https://www.test.com/api/students {"id":1,"language":"go","name":"SliverYou"} 43 application/json
Types ¶
type Client ¶
type Client struct {
BeforeOptions OptionCollection
AfterOptions OptionCollection
JSONUnmarshal Unmarshaler
XMLUnmarshal Unmarshaler
// contains filtered or unexported fields
}
Client HTTP 拓展客户端
func NewClient ¶
NewClient 新建 HTTP 拓展客户端
Example ¶
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
fmt.Println(r.Method)
fmt.Println(r.URL)
fmt.Println(string(body))
fmt.Println(r.ContentLength)
fmt.Println(r.Header.Get("Content-Type"))
fmt.Println(r.Header.Get("Authorization"))
}))
defer server.Close()
client := xreq.NewClient(
xreq.URL(server.URL),
xreq.Path("api", "/students"),
xreq.BearerAuth("abcdefgh"),
)
client.Post(xreq.BodyJSON(map[string]string{"name": "SliverYou", "language": "go"}))
}
Output: POST /api/students {"language":"go","name":"SliverYou"} 36 application/json Bearer abcdefgh
func NewClientWithConfig ¶
NewClientWithConfig 使用配置新建 HTTP 拓展客户端
func NewClientWithHTTPClient ¶
NewClientWithHTTPClient 使用 HTTP 客户端新建 HTTP 拓展客户端
func (*Client) Call ¶
Call 发起 HTTP 请求,并根据响应头部 "Content-Type" 的值将响应体内容使用特定 Unmarshaler 函数反序列化至 result 中
Example ¶
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write(body)
}))
defer server.Close()
client := xreq.NewClient(
xreq.URL(server.URL),
xreq.Path("api", "/students"),
xreq.BearerAuth("abcdefgh"),
)
result := make(map[string]string)
response, _ := client.Call(http.MethodPost, &result, xreq.BodyJSON(map[string]string{"name": "SliverYou", "language": "go"}))
fmt.Println(response.IsSuccess())
fmt.Println(response.IsError())
fmt.Println(response.ContentType())
fmt.Println(response.Size())
fmt.Println(response.String())
fmt.Println(result)
}
Output: true false application/json; charset=utf-8 36 {"language":"go","name":"SliverYou"} map[language:go name:SliverYou]
func (*Client) CallWithRequest ¶
func (c *Client) CallWithRequest(request *http.Request, result any, options ...Option) (*Response, error)
CallWithRequest 使用 *http.Request 发起 HTTP 请求,并根据响应头部 "Content-Type" 的值将响应体内容使用特定 Unmarshaler 函数反序列化至 result 中
Example ¶
package main
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write(body)
}))
defer server.Close()
client := xreq.NewClient(
xreq.BearerAuth("abcdefgh"),
)
request, _ := xreq.NewPost(server.URL,
xreq.Context(context.TODO()),
xreq.Path("api", "/students"),
xreq.BodyJSON(map[string]string{"name": "SliverYou", "language": "go"}),
)
result := make(map[string]string)
response, _ := client.CallWithRequest(request, &result)
fmt.Println(response.IsSuccess())
fmt.Println(response.IsError())
fmt.Println(response.ContentType())
fmt.Println(response.Size())
fmt.Println(response.String())
fmt.Println(result)
}
Output: true false application/json; charset=utf-8 36 {"language":"go","name":"SliverYou"} map[language:go name:SliverYou]
func (*Client) Do ¶
Do 发起 HTTP 请求
Example ¶
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
fmt.Println(r.Method)
fmt.Println(r.URL)
fmt.Println(string(body))
fmt.Println(r.ContentLength)
fmt.Println(r.Header.Get("Content-Type"))
fmt.Println(r.Header.Get("Authorization"))
}))
defer server.Close()
client := xreq.NewClient(
xreq.URL(server.URL),
xreq.Path("api", "/students"),
xreq.BearerAuth("abcdefgh"),
)
client.Do(http.MethodPost, xreq.BodyJSON(map[string]string{"name": "SliverYou", "language": "go"}))
}
Output: POST /api/students {"language":"go","name":"SliverYou"} 36 application/json Bearer abcdefgh
func (*Client) DoWithRequest ¶
DoWithRequest 使用 *http.Request 发起 HTTP 请求
Example ¶
package main
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
fmt.Println(r.Method)
fmt.Println(r.URL)
fmt.Println(string(body))
fmt.Println(r.ContentLength)
fmt.Println(r.Header.Get("Content-Type"))
fmt.Println(r.Header.Get("Authorization"))
}))
defer server.Close()
client := xreq.NewClient(
xreq.BearerAuth("abcdefgh"),
)
request, _ := xreq.NewPost(server.URL,
xreq.Context(context.TODO()),
xreq.Path("api", "/students"),
xreq.BodyJSON(map[string]string{"name": "SliverYou", "language": "go"}),
)
client.DoWithRequest(request)
}
Output: POST /api/students {"language":"go","name":"SliverYou"} 36 application/json Bearer abcdefgh
func (*Client) GetHTTPClient ¶
GetHTTPClient 获取 HTTP 客户端
func (*Client) SetAfterOptions ¶
SetAfterOptions 设置后可选参数
func (*Client) SetHTTPClient ¶
SetHTTPClient 设置 HTTP 客户端
func (*Client) SetJSONUnmarshaler ¶
func (c *Client) SetJSONUnmarshaler(unmarshaler Unmarshaler) *Client
SetJSONUnmarshaler 设置 json 反序列化器
func (*Client) SetTLSClientConfig ¶
SetTLSClientConfig 设置 TLS 配置
func (*Client) SetTimeout ¶
SetTimeout 设置 HTTP 请求超时时间
func (*Client) SetTransport ¶
func (c *Client) SetTransport(transport http.RoundTripper) *Client
SetTransport 设置传输器
func (*Client) SetXMLUnmarshaler ¶
func (c *Client) SetXMLUnmarshaler(unmarshaler Unmarshaler) *Client
SetXMLUnmarshaler 设置 xml 反序列化器
type Option ¶
type Option interface {
// Apply 将可选参数应用于 http 请求中
Apply(request *http.Request) (*http.Request, error)
}
Option http 请求可选参数应用器接口
func Accept ¶
Accept 将 "Accept" 头部应用于 http 请求的 header 中
Example ¶
package main
import (
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.Accept("application/json"),
)
fmt.Println(request.Header.Get("Accept"))
}
Output: application/json
func AddCookies ¶
AddCookies 将 *http.Cookie 列表添加到 http 请求中
Example ¶
package main
import (
"fmt"
"net/http"
"time"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.AddCookies(
&http.Cookie{
Name: "cookie-1", Value: "v$1",
Expires: time.Now().Add(time.Hour),
},
&http.Cookie{
Name: "cookie-2", Value: "v$2",
Expires: time.Now().Add(time.Hour),
},
),
)
fmt.Println(request.Header.Get("Cookie"))
}
Output: cookie-1=v$1; cookie-2=v$2
func AddPath ¶
AddPath 使用 path.Join 将路径分段连接并添加到 http 请求的 url path 中
Example ¶
package main
import (
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.AddPath("/tests", "1234/", "cases"),
)
fmt.Println(request.URL.Path)
}
Output: /api/tests/1234/cases
func AddQueries ¶
AddQueries 将 url.Values 添加到 http 请求的 url query 中
Example ¶
package main
import (
"fmt"
"net/url"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.AddQueries(url.Values{
"page": {"10"},
"page_size": {"50"},
}),
xreq.AddQueries(url.Values{
"page": {"20", "30"},
}),
)
fmt.Println(request.URL.Query().Encode())
}
Output: page=10&page=20&page=30&page_size=50
func AddQuery ¶
AddQuery 将 key 和 value 添加到 http 请求的 url query 中
Example ¶
package main
import (
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.AddQuery("page", 1),
xreq.AddQuery("page", 2),
xreq.AddQuery("page", 3),
)
fmt.Println(request.URL.Query().Encode())
}
Output: page=1&page=2&page=3
func AddQueryMap ¶
AddQueryMap 将 map[string]any 添加到 http 请求的 url query 中
Example ¶
package main
import (
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.AddQueryMap(map[string]any{
"page": 10,
"page_size": 50,
}),
xreq.AddQueryMap(map[string]any{
"page": 20,
}),
)
fmt.Println(request.URL.Query().Encode())
}
Output: page=10&page=20&page_size=50
func Authorization ¶
Authorization 将 "Authorization" 头部应用于 http 请求的 header 中
Example ¶
package main
import (
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.Authorization("abcdefgh"),
)
fmt.Println(request.Header.Get("Authorization"))
}
Output: abcdefgh
func BasicAuth ¶
BasicAuth 构建 "Authorization: Basic <base64Encode(username:password)>" 头部并应用于 http 请求的 header 中
Example ¶
package main
import (
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.BasicAuth("SliverYou", "123456"),
)
fmt.Println(request.Header.Get("Authorization"))
}
Output: Basic U2xpdmVyWW91OjEyMzQ1Ng==
func BearerAuth ¶
BearerAuth 构建 "Authorization: Bearer <token>" 头部并应用于 http 请求的 header 中
Example ¶
package main
import (
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.BearerAuth("abcdefgh"),
)
fmt.Println(request.Header.Get("Authorization"))
}
Output: Bearer abcdefgh
func Body ¶
func Body(body io.ReadCloser) Option
Body 将 io.ReadCloser 应用于 http 请求的 body 中
Example ¶
package main
import (
"fmt"
"io"
"strings"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewPost("https://www.test.com/api",
xreq.Body(io.NopCloser(strings.NewReader("example body"))),
)
body, _ := io.ReadAll(request.Body)
fmt.Println(string(body))
}
Output: example body
func BodyBytes ¶
BodyBytes 将 []byte 应用于 http 请求的 body 中
Example ¶
package main
import (
"fmt"
"io"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewPost("https://www.test.com/api",
xreq.BodyBytes([]byte("example body")),
)
body, _ := io.ReadAll(request.Body)
fmt.Println(string(body))
fmt.Println(request.ContentLength)
}
Output: example body 12
func BodyForm ¶
BodyForm 将 url.Values 应用于 http 请求的 body 中,并设置 "Content-Type" 头部为 "application/x-www-form-urlencoded"
Example ¶
package main
import (
"fmt"
"io"
"net/url"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewPost("https://www.test.com/api",
xreq.BodyForm(url.Values{
"page": {"10"},
"page_size": {"50"},
}),
)
body, _ := io.ReadAll(request.Body)
fmt.Println(string(body))
fmt.Println(request.ContentLength)
fmt.Println(request.Header.Get("Content-Type"))
}
Output: page=10&page_size=50 20 application/x-www-form-urlencoded
func BodyFormMap ¶
BodyFormMap 将 map[string]any 应用于 http 请求的 body 中,并设置 "Content-Type" 头部为 "application/x-www-form-urlencoded"
Example ¶
package main
import (
"fmt"
"io"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewPost("https://www.test.com/api",
xreq.BodyFormMap(map[string]any{
"page": 10,
"page_size": 50,
}),
)
body, _ := io.ReadAll(request.Body)
fmt.Println(string(body))
fmt.Println(request.ContentLength)
fmt.Println(request.Header.Get("Content-Type"))
}
Output: page=10&page_size=50 20 application/x-www-form-urlencoded
func BodyJSON ¶
BodyJSON 使用 Marshaler 将 obj 序列化为 json 格式应用于 http 请求的 body 中,并设置 "Content-Type" 头部为 "application/json"
Example ¶
package main
import (
"encoding/json"
"fmt"
"io"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewPost("https://www.test.com/api",
xreq.BodyJSON(map[string]string{"name": "SliverYou", "language": "go"}),
)
body, _ := io.ReadAll(request.Body)
fmt.Println(string(body))
fmt.Println(request.ContentLength)
fmt.Println(request.Header.Get("Content-Type"))
request, _ = xreq.NewPost("https://www.test.com/api",
xreq.BodyJSON(map[string]string{"name": "SliverYou", "language": "go"},
func(v any) ([]byte, error) {
return json.MarshalIndent(v, "", "\t")
},
),
)
body, _ = io.ReadAll(request.Body)
fmt.Println(string(body) == "{\n\t\"language\": \"go\",\n\t\"name\": \"SliverYou\"\n}")
fmt.Println(request.ContentLength)
fmt.Println(request.Header.Get("Content-Type"))
}
Output: {"language":"go","name":"SliverYou"} 36 application/json true 43 application/json
func BodyReader ¶
BodyReader 将 io.Reader 应用于 http 请求的 body 中
Example ¶
package main
import (
"fmt"
"io"
"strings"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewPost("https://www.test.com/api",
xreq.BodyReader(strings.NewReader("example body")),
)
body, _ := io.ReadAll(request.Body)
fmt.Println(string(body))
fmt.Println(request.ContentLength)
}
Output: example body 12
func BodyString ¶
BodyString 将 string 应用于 http 请求的 body 中
Example ¶
package main
import (
"fmt"
"io"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewPost("https://www.test.com/api",
xreq.BodyString("example body"),
)
body, _ := io.ReadAll(request.Body)
fmt.Println(string(body))
fmt.Println(request.ContentLength)
}
Output: example body 12
func BodyXML ¶
BodyXML 使用 Marshaler 将 obj 序列化为 xml 格式应用于 http 请求的 body 中,并设置 "Content-Type" 头部为 "application/xml"
Example ¶
package main
import (
"encoding/xml"
"fmt"
"io"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
type Data struct {
XMLName xml.Name `xml:"Response"`
Code uint32 `xml:"Code"`
Message string `xml:"Message"`
Data any `xml:"Data"`
}
data := Data{
Code: 0,
Message: "ok",
Data: "success",
}
request, _ := xreq.NewPost("https://www.test.com/api",
xreq.BodyXML(data),
)
body, _ := io.ReadAll(request.Body)
fmt.Println(string(body))
fmt.Println(request.ContentLength)
fmt.Println(request.Header.Get("Content-Type"))
request, _ = xreq.NewPost("https://www.test.com/api",
xreq.BodyXML(data, func(v any) ([]byte, error) {
return xml.MarshalIndent(v, "", " ")
}),
)
body, _ = io.ReadAll(request.Body)
fmt.Println(string(body) == "<Response>\n <Code>0</Code>\n <Message>ok</Message>\n <Data>success</Data>\n</Response>")
fmt.Println(request.ContentLength)
fmt.Println(request.Header.Get("Content-Type"))
}
Output: <Response><Code>0</Code><Message>ok</Message><Data>success</Data></Response> 76 application/xml true 86 application/xml
func CacheControl ¶
CacheControl 将 "Cache-Control" 头部应用于 http 请求的 header 中
Example ¶
package main
import (
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.CacheControl("no-cache"),
)
fmt.Println(request.Header.Get("Cache-Control"))
}
Output: no-cache
func ContentLength ¶
ContentLength 将 contentLength 应用于 http 请求中
Example ¶
package main
import (
"fmt"
"io"
"strings"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
s := "example body"
request, _ := xreq.NewPost("https://www.test.com/api",
xreq.Body(io.NopCloser(strings.NewReader(s))),
xreq.ContentLength(len(s)),
)
body, _ := io.ReadAll(request.Body)
fmt.Println(string(body))
fmt.Println(request.ContentLength)
}
Output: example body 12
func ContentType ¶
ContentType 将 "Content-Type" 头部应用于 http 请求的 header 中
Example ¶
package main
import (
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.ContentType("application/json"),
)
fmt.Println(request.Header.Get("Content-Type"))
}
Output: application/json
func Context ¶
Context 将 context.Context 应用于 http 请求中
Example ¶
package main
import (
"context"
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.Context(context.Background()),
)
fmt.Println(request.Context())
}
Output: context.Background
func ContextValue ¶
ContextValue 将 key 和 value 应用于 http 请求的 context 中
Example ¶
package main
import (
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.ContextValue("key", "value"),
)
fmt.Println(request.Context().Value("key"))
}
Output: value
func Dump ¶
Dump 转储 http 请求信息并将其写入 io.Writer 中
Example ¶
package main
import (
"bytes"
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
var buffer bytes.Buffer
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.BodyString("example body"),
xreq.Dump(&buffer),
)
fmt.Println(request.ContentLength)
fmt.Println(buffer.String() == "GET /api HTTP/1.1\r\nHost: www.test.com\r\n\r\nexample body")
}
Output: 12 true
func Header ¶
Header 将 key 和 values 应用于 http 请求的 header 中
Example ¶
package main
import (
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.Header("key", "value1"),
xreq.Header("key", "value2", "value3"),
)
fmt.Println(request.Header.Get("key"))
}
Output: value2, value3
func HeaderMap ¶
HeaderMap 将 map[string]string 应用于 http 请求的 header 中
Example ¶
package main
import (
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.HeaderMap(map[string]string{
"a": "1",
"b": "2",
}),
)
fmt.Println(request.Header)
}
Output: map[A:[1] B:[2]]
func Headers ¶
Headers 将 http.Header 应用于 http 请求的 header 中
Example ¶
package main
import (
"fmt"
"net/http"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.Headers(http.Header{
"a": {"1"},
"b": {"2", "3"},
}),
xreq.Headers(http.Header{
"a": {"2", "3"},
"c": {"4"},
}),
)
fmt.Println(request.Header)
}
Output: map[A:[2, 3] B:[2, 3] C:[4]]
func Host ¶
Host 将 host 应用于 http 请求中
Example ¶
package main
import (
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.Host("api.test.com"),
)
fmt.Println(request.Host)
fmt.Println(request.URL)
}
Output: api.test.com https://api.test.com/api
func Method ¶
Method 将 method 应用于 http 请求中
Example ¶
package main
import (
"fmt"
"net/http"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.New("", "https://www.test.com/api", xreq.Method(http.MethodPost))
fmt.Println(request.Method)
fmt.Println(request.URL)
}
Output: POST https://www.test.com/api
func Path ¶
Path 使用 path.Join 将路径分段连接并应用于 http 请求的 url path 中
Example ¶
package main
import (
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com",
xreq.Path("api", "/tests", "1234/", "cases"),
)
fmt.Println(request.URL.Path)
}
Output: /api/tests/1234/cases
func Queries ¶
Queries 将 url.Values 应用于 http 请求的 url query 中
Example ¶
package main
import (
"fmt"
"net/url"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.Queries(url.Values{
"page": {"10"},
"page_size": {"50"},
}),
xreq.Queries(url.Values{
"page": {"20"},
"page_size": {"50"},
}),
)
fmt.Println(request.URL.Query().Encode())
}
Output: page=20&page_size=50
func Query ¶
Query 将 key 和 value 应用于 http 请求的 url query 中
Example ¶
package main
import (
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.Query("page", 1),
xreq.Query("page", 2),
xreq.Query("page", 3),
)
fmt.Println(request.URL.Query().Encode())
}
Output: page=3
func QueryMap ¶
QueryMap 将 map[string]any 应用于 http 请求的 url query 中
Example ¶
package main
import (
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.QueryMap(map[string]any{
"page": 10,
"page_size": 50,
}),
xreq.QueryMap(map[string]any{
"page": 20,
"page_size": 50,
}),
)
fmt.Println(request.URL.Query().Encode())
}
Output: page=20&page_size=50
func RawURL ¶
RawURL 将 *url.URL 应用于 http 请求中
Example ¶
package main
import (
"fmt"
"net/url"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
rawURL, _ := url.Parse("http://www.test.com/api")
rawURL.Scheme = "https"
request, _ := xreq.NewGet("", xreq.RawURL(rawURL))
fmt.Println(request.URL)
}
Output: https://www.test.com/api
func Referer ¶
Referer 将 "Referer" 头部应用于 http 请求的 header 中
Example ¶
package main
import (
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.Referer("https://test.com"),
)
fmt.Println(request.Header.Get("Referer"))
}
Output: https://test.com
func Scheme ¶
Scheme 将 scheme 应用于 http 请求的 url 中
Example ¶
package main
import (
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.Scheme("http"),
)
fmt.Println(request.URL)
}
Output: http://www.test.com/api
func TokenAuth ¶
TokenAuth 构建 "Authorization: Token <token>" 头部并应用于 http 请求的 header 中
Example ¶
package main
import (
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.TokenAuth("abcdefgh"),
)
fmt.Println(request.Header.Get("Authorization"))
}
Output: Token abcdefgh
func URL ¶
URL 将 url 应用于 http 请求中
Example ¶
package main
import (
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("", xreq.URL("https://www.test.com/api"))
fmt.Println(request.URL)
}
Output: https://www.test.com/api
func User ¶
User 将 *url.Userinfo 应用于 http 请求的 url 中
Example ¶
package main
import (
"fmt"
"net/url"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
user := url.UserPassword("SliverYou", "123456")
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.User(user),
)
fmt.Println(request.URL)
}
Output: https://SliverYou:123456@www.test.com/api
func UserAgent ¶
UserAgent 将 "User-Agent" 头部应用于 http 请求的 header 中
Example ¶
package main
import (
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.UserAgent("xreq"),
)
fmt.Println(request.Header.Get("User-Agent"))
}
Output: xreq
func UserPassword ¶
UserPassword 将 username 和 password 应用于 http 请求的 url 中
Example ¶
package main
import (
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.UserPassword("SliverYou", "123456"),
)
fmt.Println(request.URL)
}
Output: https://SliverYou:123456@www.test.com/api
func Username ¶
Username 将 username 应用于 http 请求的 url 中
Example ¶
package main
import (
"fmt"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
request, _ := xreq.NewGet("https://www.test.com/api",
xreq.Username("SliverYou"),
)
fmt.Println(request.URL)
}
Output: https://SliverYou@www.test.com/api
type OptionCollection ¶
type OptionCollection []Option
OptionCollection 可选参数集合
func (OptionCollection) With ¶
func (oc OptionCollection) With(withOptions ...Option) OptionCollection
With 添加可选参数列表并返回新的可选参数集合
type OptionFunc ¶
OptionFunc 可选参数生成函数
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
token := "custom.token.1"
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.Header.Get("Authorization"))
}))
defer server.Close()
client := xreq.NewClientWithHTTPClient(server.Client(),
xreq.URL(server.URL),
xreq.OptionFunc(func(request *http.Request) (*http.Request, error) {
return xreq.BearerAuth(token).Apply(request)
}),
)
client.Get()
token = "custom.token.2"
client.Get()
}
Output: Bearer custom.token.1 Bearer custom.token.2
type Response ¶
Response HTTP 拓展响应
Example ¶
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write(body)
}))
defer server.Close()
client := xreq.NewClient(
xreq.URL(server.URL),
xreq.Path("api", "/students"),
xreq.BearerAuth("abcdefgh"),
)
response, _ := client.Post(xreq.BodyJSON(map[string]string{"name": "SliverYou", "language": "go"}))
result := make(map[string]string)
response.Unmarshal(&result)
fmt.Println(response.IsSuccess())
fmt.Println(response.IsError())
fmt.Println(response.ContentType())
fmt.Println(response.Size())
fmt.Println(response.String())
fmt.Println(result)
}
Output: true false application/json; charset=utf-8 36 {"language":"go","name":"SliverYou"} map[language:go name:SliverYou]
func Do ¶
Do 通过 DefaultClient 发起 HTTP 请求
Example ¶
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"github.com/sliveryou/micro-pkg/xhttp/xreq"
)
func main() {
server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
fmt.Println(r.Method)
fmt.Println(r.URL)
fmt.Println(string(body))
fmt.Println(r.ContentLength)
fmt.Println(r.Header.Get("Content-Type"))
fmt.Println(r.Header.Get("Authorization"))
}))
defer server.Close()
xreq.Do(http.MethodPost, server.URL,
xreq.Path("api", "/students"),
xreq.BearerAuth("abcdefgh"),
xreq.BodyJSON(map[string]string{"name": "SliverYou", "language": "go"}),
)
}
Output: POST /api/students {"language":"go","name":"SliverYou"} 36 application/json Bearer abcdefgh
func (*Response) ContentType ¶
ContentType 返回响应头部 "Content-Type" 的值
func (*Response) GetAllHeadersString ¶
GetAllHeadersString 返回 string 形式的所有响应头部内容
func (*Response) JSONUnmarshal ¶
JSONUnmarshal 将 JSON 形式的响应体内容使用 Client.JSONUnmarshal 反序列化到指定对象中
func (*Response) XMLUnmarshal ¶
XMLUnmarshal 将 XML 形式的响应体内容使用 Client.XMLUnmarshal 反序列化到指定对象中