xreq

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 11, 2024 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// DefaultConfig 获取默认 HTTP 客户端配置
	DefaultConfig = xhttp.DefaultConfig
	// NewHTTPClient 新建 HTTP 客户端(不传递配置时,将使用默认配置 DefaultConfig)
	NewHTTPClient = xhttp.NewHTTPClient

	// DefaultHTTPClient 默认 HTTP 客户端
	DefaultHTTPClient = NewHTTPClient()
	// DefaultClient 默认 HTTP 拓展客户端
	DefaultClient = NewClient()
)

Functions

func Apply

func Apply(request *http.Request, options ...Option) (*http.Request, error)

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

func New(method, url string, options ...Option) (*http.Request, error)

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

func NewDelete(url string, options ...Option) (*http.Request, error)

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

func NewGet(url string, options ...Option) (*http.Request, error)

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

func NewHead(url string, options ...Option) (*http.Request, error)

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

func NewOptions(url string, options ...Option) (*http.Request, error)

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

func NewPatch(url string, options ...Option) (*http.Request, error)

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

func NewPost(url string, options ...Option) (*http.Request, error)

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

func NewPut(url string, options ...Option) (*http.Request, error)

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

func NewClient(beforeOptions ...Option) *Client

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

func NewClientWithConfig(config Config, beforeOptions ...Option) *Client

NewClientWithConfig 使用配置新建 HTTP 拓展客户端

func NewClientWithHTTPClient

func NewClientWithHTTPClient(hc *http.Client, beforeOptions ...Option) *Client

NewClientWithHTTPClient 使用 HTTP 客户端新建 HTTP 拓展客户端

func (*Client) Call

func (c *Client) Call(method string, result any, options ...Option) (*Response, error)

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) Delete

func (c *Client) Delete(options ...Option) (*Response, error)

Delete 发起 HTTP DELETE 请求

func (*Client) Do

func (c *Client) Do(method string, options ...Option) (*Response, error)

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

func (c *Client) DoWithRequest(request *http.Request, options ...Option) (*Response, error)

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) Get

func (c *Client) Get(options ...Option) (*Response, error)

Get 发起 HTTP GET 请求

func (*Client) GetHTTPClient

func (c *Client) GetHTTPClient() *http.Client

GetHTTPClient 获取 HTTP 客户端

func (*Client) Head

func (c *Client) Head(options ...Option) (*Response, error)

Head 发起 HTTP HEAD 请求

func (*Client) Options

func (c *Client) Options(options ...Option) (*Response, error)

Options 发起 HTTP OPTIONS 请求

func (*Client) Patch

func (c *Client) Patch(options ...Option) (*Response, error)

Patch 发起 HTTP PATCH 请求

func (*Client) Post

func (c *Client) Post(options ...Option) (*Response, error)

Post 发起 HTTP POST 请求

func (*Client) Put

func (c *Client) Put(options ...Option) (*Response, error)

Put 发起 HTTP PUT 请求

func (*Client) SetAfterOptions

func (c *Client) SetAfterOptions(afterOptions ...Option) *Client

SetAfterOptions 设置后可选参数

func (*Client) SetHTTPClient

func (c *Client) SetHTTPClient(hc *http.Client) *Client

SetHTTPClient 设置 HTTP 客户端

func (*Client) SetJSONUnmarshaler

func (c *Client) SetJSONUnmarshaler(unmarshaler Unmarshaler) *Client

SetJSONUnmarshaler 设置 json 反序列化器

func (*Client) SetProxy

func (c *Client) SetProxy(proxyURL string) *Client

SetProxy 设置请求代理

func (*Client) SetTLSClientConfig

func (c *Client) SetTLSClientConfig(config *tls.Config) *Client

SetTLSClientConfig 设置 TLS 配置

func (*Client) SetTimeout

func (c *Client) SetTimeout(timeout time.Duration) *Client

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 Config

type Config = xhttp.Config

Config HTTP 客户端配置

type Marshaler

type Marshaler = func(v any) ([]byte, error)

Marshaler 序列化函数

type Option

type Option interface {
	// Apply 将可选参数应用于 http 请求中
	Apply(request *http.Request) (*http.Request, error)
}

Option http 请求可选参数应用器接口

func Accept

func Accept(accept string) Option

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

func AddCookies(cookies ...*http.Cookie) Option

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

func AddPath(segments ...string) Option

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

func AddQueries(queries stdurl.Values) Option

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

func AddQuery(key string, value any) Option

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

func AddQueryMap(queryMap map[string]any) Option

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

func Authorization(authorization string) Option

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

func BasicAuth(username, password string) Option

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

func BearerAuth(token string) Option

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

func BodyBytes(body []byte) Option

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

func BodyForm(body stdurl.Values) Option

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

func BodyFormMap(formMap map[string]any) Option

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

func BodyJSON(obj any, marshaler ...Marshaler) Option

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

func BodyReader(body io.Reader) Option

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

func BodyString(body string) Option

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

func BodyXML(obj any, marshaler ...Marshaler) Option

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

func CacheControl(cacheControl string) Option

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

func ContentLength(contentLength int) Option

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

func ContentType(contentType string) Option

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

func Context(ctx context.Context) Option

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

func ContextValue(key, value any) Option

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

func Dump(w io.Writer) Option

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(key string, values ...string) Option

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

func HeaderMap(headerMap map[string]string) Option

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

func Headers(headers http.Header) Option

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

func Host(host string) Option

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

func Method(method string) Option

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

func Path(segments ...string) Option

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

func Queries(queries stdurl.Values) Option

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

func Query(key string, value any) Option

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

func QueryMap(queryMap map[string]any) Option

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

func RawURL(url *stdurl.URL) Option

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

func Referer(referer string) Option

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

func Scheme(scheme string) Option

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

func TokenAuth(token string) Option

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

func URL(url string) Option

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

func User(user *stdurl.Userinfo) Option

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

func UserAgent(userAgent string) Option

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

func UserPassword(username, password string) Option

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

func Username(username string) Option

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) Apply

func (oc OptionCollection) Apply(request *http.Request) (*http.Request, error)

Apply 将可选参数集合应用于 http 请求中

func (OptionCollection) With

func (oc OptionCollection) With(withOptions ...Option) OptionCollection

With 添加可选参数列表并返回新的可选参数集合

type OptionFunc

type OptionFunc func(request *http.Request) (*http.Request, error)

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

func (OptionFunc) Apply

func (f OptionFunc) Apply(request *http.Request) (*http.Request, error)

Apply 将可选参数生成函数应用于 http 请求中

type Response

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

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 Delete

func Delete(url string, options ...Option) (*Response, error)

Delete 通过 DefaultClient 发起 HTTP DELETE 请求

func Do

func Do(method, url string, options ...Option) (*Response, error)

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 Get

func Get(url string, options ...Option) (*Response, error)

Get 通过 DefaultClient 发起 HTTP GET 请求

func Head(url string, options ...Option) (*Response, error)

Head 通过 DefaultClient 发起 HTTP HEAD 请求

func Options

func Options(url string, options ...Option) (*Response, error)

Options 通过 DefaultClient 发起 HTTP OPTIONS 请求

func Patch

func Patch(url string, options ...Option) (*Response, error)

Patch 通过 DefaultClient 发起 HTTP PATCH 请求

func Post

func Post(url string, options ...Option) (*Response, error)

Post 通过 DefaultClient 发起 HTTP POST 请求

func Put

func Put(url string, options ...Option) (*Response, error)

Put 通过 DefaultClient 发起 HTTP PUT 请求

func (*Response) Bytes

func (r *Response) Bytes() []byte

Bytes 返回 []byte 形式的响应体内容

func (*Response) ContentType

func (r *Response) ContentType() string

ContentType 返回响应头部 "Content-Type" 的值

func (*Response) Cookies

func (r *Response) Cookies() []*http.Cookie

Cookies 返回响应 cookie 列表

func (*Response) GetAllHeadersString

func (r *Response) GetAllHeadersString() string

GetAllHeadersString 返回 string 形式的所有响应头部内容

func (*Response) Header

func (r *Response) Header() http.Header

Header 返回响应头部

func (*Response) IsError

func (r *Response) IsError() bool

IsError 判断响应状态码是否为错误状态(code >= 400)

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

IsSuccess 判断响应状态码是否为成功状态(code >= 200 and <= 299)

func (*Response) JSONUnmarshal

func (r *Response) JSONUnmarshal(v any) error

JSONUnmarshal 将 JSON 形式的响应体内容使用 Client.JSONUnmarshal 反序列化到指定对象中

func (*Response) Proto

func (r *Response) Proto() string

Proto 返回响应协议

func (*Response) RawBody

func (r *Response) RawBody() io.ReadCloser

RawBody 返回原始响应体

func (*Response) ReceivedAt

func (r *Response) ReceivedAt() time.Time

ReceivedAt 响应接收时间

func (*Response) Size

func (r *Response) Size() int64

Size 返回响应体大小

func (*Response) Status

func (r *Response) Status() string

Status 返回响应状态

Example: 200 OK

func (*Response) StatusCode

func (r *Response) StatusCode() int

StatusCode 返回响应状态码

Example: 200

func (*Response) String

func (r *Response) String() string

String 返回 string 形式的响应体内容

func (*Response) Unmarshal

func (r *Response) Unmarshal(v any) error

Unmarshal 根据响应头部 "Content-Type" 的值将响应体内容使用特定 Unmarshaler 函数反序列化到指定对象中

func (*Response) XMLUnmarshal

func (r *Response) XMLUnmarshal(v any) error

XMLUnmarshal 将 XML 形式的响应体内容使用 Client.XMLUnmarshal 反序列化到指定对象中

type Unmarshaler

type Unmarshaler = func(data []byte, v any) error

Unmarshaler 反序列化函数

Jump to

Keyboard shortcuts

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