requests

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2026 License: MIT Imports: 13 Imported by: 0

README

go-requests

一个轻量级的、受 Python requests 启发的 Go HTTP 客户端。API 采用函数优先设计,使用小型可组合选项。旨在覆盖最常见的用例(核心 80%),避免过度抽象。

特性

  • 简单的 Get/Post/Put/Patch/Delete/Head/Options 辅助函数
  • 基于选项的请求配置(headers, query, body, timeout, proxy, redirect)
  • 响应辅助函数:Bytes, Text, JSON
  • 清晰的错误语义,带有类型化错误
  • 可选的 Session 用于设置默认值
  • 可选的 gzip 自动解压

安装

go get github.com/CareyWang/go-requests

快速开始

package main

import (
	"fmt"
	"log"

	requests "github.com/CareyWang/go-requests"
)

func main() {
	resp, err := requests.Get("https://httpbin.org/get",
		requests.WithQuery(map[string]string{"q": "golang"}),
		requests.WithHeader("X-Trace", "abc"),
	)
	if err != nil {
		log.Fatal(err)
	}
	text, _ := resp.Text()
	fmt.Println(text)
}

使用示例

POST JSON
resp, err := requests.Post("https://httpbin.org/post",
	requests.WithJSON(map[string]any{"name": "alice"}),
)
if err != nil {
	log.Fatal(err)
}
fmt.Println(resp.StatusCode)
表单数据
resp, err := requests.Post("https://httpbin.org/post",
	requests.WithForm(map[string]string{"a": "1", "b": "2"}),
)
原始请求体
body := strings.NewReader("raw payload")
resp, err := requests.Post("https://httpbin.org/post",
	requests.WithBody(body),
	requests.WithHeader("Content-Type", "text/plain"),
)
超时
resp, err := requests.Get("https://httpbin.org/delay/2",
	requests.WithTimeout(1*time.Second),
)
if errors.Is(err, requests.ErrTimeout) {
	log.Println("timeout")
}
gzip 自动解压
resp, err := requests.Get("https://example.com",
	requests.WithHeader("Accept-Encoding", "gzip"),
	requests.WithDecompressGzip(),
)
text, _ := resp.Text()
重定向控制
// max=0 禁用重定向
resp, err := requests.Get("https://httpbin.org/redirect/1",
	requests.WithRedirect(0),
)
代理
resp, err := requests.Get("https://example.com",
	requests.WithProxy("http://127.0.0.1:8080"),
)
Session 默认值
s := requests.NewSession(
	requests.WithHeader("User-Agent", "httpclient"),
	requests.WithTimeout(5*time.Second),
)

resp, err := s.Get("https://httpbin.org/get")

API 文档

顶级方法
func Get(url string, opts ...Option) (*Response, error)
func Post(url string, opts ...Option) (*Response, error)
func Put(url string, opts ...Option) (*Response, error)
func Patch(url string, opts ...Option) (*Response, error)
func Delete(url string, opts ...Option) (*Response, error)
func Head(url string, opts ...Option) (*Response, error)
func Options(url string, opts ...Option) (*Response, error)
Session
type Session struct{}

func NewSession(opts ...Option) *Session
func (s *Session) Get(url string, opts ...Option) (*Response, error)
func (s *Session) Post(url string, opts ...Option) (*Response, error)
func (s *Session) Put(url string, opts ...Option) (*Response, error)
func (s *Session) Patch(url string, opts ...Option) (*Response, error)
func (s *Session) Delete(url string, opts ...Option) (*Response, error)
func (s *Session) Head(url string, opts ...Option) (*Response, error)
func (s *Session) Options(url string, opts ...Option) (*Response, error)
Options
type Option func(*Request)

func WithHeader(key, value string) Option
func WithHeaders(h map[string]string) Option
func WithQuery(q map[string]string) Option
func WithTimeout(d time.Duration) Option
func WithDecompressGzip() Option
func WithJSON(v any) Option
func WithForm(values map[string]string) Option
func WithBody(body io.Reader) Option
func WithCookies(cookies ...*http.Cookie) Option
func WithProxy(rawURL string) Option
func WithRedirect(max int) Option
Response
type Response struct {
	Raw        *http.Response
	StatusCode int
	Headers    http.Header
}

func (r *Response) Bytes() ([]byte, error)
func (r *Response) Text() (string, error)
func (r *Response) JSON(v any) error
错误
var (
	ErrRequest = fmt.Errorf("request error")
	ErrNetwork = fmt.Errorf("network error")
	ErrTimeout = fmt.Errorf("timeout")
	ErrStatus  = fmt.Errorf("unexpected status")
	ErrResponse = fmt.Errorf("response error")
	ErrResponseNil = fmt.Errorf("nil response")
	ErrNoContent   = fmt.Errorf("empty response body")
)

type StatusError struct {
	StatusCode int
	Response   *Response
}

错误处理说明

  • 非 2xx 响应返回 *StatusErrorerrors.Is(err, ErrStatus) 为 true
  • 超时返回 errors.Is(err, ErrTimeout)
  • 其他传输故障返回 errors.Is(err, ErrNetwork)
  • Response.JSON 在空响应体时返回 ErrNoContent
  • Response.Bytes 在响应或响应体为 nil 时返回 ErrResponseNil
  • Response.Bytes 在读取或解压失败时返回 ErrResponse
  • Response.JSON 在解码失败时返回 ErrResponse

许可证

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrRequest indicates a request build or configuration error.
	ErrRequest = fmt.Errorf("request error")
	// ErrNetwork indicates a transport/network error.
	ErrNetwork = fmt.Errorf("network error")
	// ErrTimeout indicates a timeout error.
	ErrTimeout = fmt.Errorf("timeout")
	// ErrStatus indicates a non-2xx HTTP status.
	ErrStatus = fmt.Errorf("unexpected status")
	// ErrResponse indicates a response read or decode error.
	ErrResponse = fmt.Errorf("response error")
	// ErrResponseNil indicates a nil response or body.
	ErrResponseNil = fmt.Errorf("nil response")
	// ErrNoContent indicates an empty response body.
	ErrNoContent = fmt.Errorf("empty response body")
)

Functions

This section is empty.

Types

type Option

type Option func(*Request)

Option mutates a Request.

func WithBody

func WithBody(body io.Reader) Option

WithBody sets a raw body reader. Note: the reader is used as-is; do not reuse it across concurrent requests.

func WithCookies

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

WithCookies adds cookies to the request.

func WithDecompressGzip added in v1.0.1

func WithDecompressGzip() Option

WithDecompressGzip enables gzip auto-decompression for response bodies.

func WithForm

func WithForm(values map[string]string) Option

WithForm encodes form values and sets Content-Type.

func WithHeader

func WithHeader(key, value string) Option

WithHeader sets a single header value (overwrites existing).

func WithHeaders

func WithHeaders(h map[string]string) Option

WithHeaders sets multiple headers (overwrites existing keys).

func WithJSON

func WithJSON(v any) Option

WithJSON encodes v as JSON and sets Content-Type if missing.

func WithProxy

func WithProxy(rawURL string) Option

WithProxy sets a proxy URL for the request.

func WithQuery

func WithQuery(q map[string]string) Option

WithQuery appends query parameters.

func WithRedirect

func WithRedirect(max int) Option

WithRedirect sets max redirects. max=0 disables redirects.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets per-request timeout.

type Request

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

Request holds request state built from options.

type Response

type Response struct {
	Raw        *http.Response
	StatusCode int
	Headers    http.Header
	// contains filtered or unexported fields
}

Response wraps http.Response with convenience helpers.

func Delete

func Delete(ctx context.Context, url string, opts ...Option) (*Response, error)

Delete sends a DELETE request.

func Get

func Get(ctx context.Context, url string, opts ...Option) (*Response, error)

Get sends a GET request.

func Head(ctx context.Context, url string, opts ...Option) (*Response, error)

Head sends a HEAD request.

func Options

func Options(ctx context.Context, url string, opts ...Option) (*Response, error)

Options sends an OPTIONS request.

func Patch

func Patch(ctx context.Context, url string, opts ...Option) (*Response, error)

Patch sends a PATCH request.

func Post

func Post(ctx context.Context, url string, opts ...Option) (*Response, error)

Post sends a POST request.

func Put

func Put(ctx context.Context, url string, opts ...Option) (*Response, error)

Put sends a PUT request.

func (*Response) Bytes

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

Bytes reads and caches the response body and returns ErrResponseNil on nil responses.

func (*Response) JSON

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

JSON decodes the response body into v and returns ErrNoContent on empty bodies.

func (*Response) Text

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

Text reads the response body as string.

type Session

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

Session holds default options for requests.

func NewSession

func NewSession(opts ...Option) *Session

NewSession creates a new session with default options.

func (*Session) Delete

func (s *Session) Delete(ctx context.Context, url string, opts ...Option) (*Response, error)

Delete sends a DELETE request using session defaults.

func (*Session) Get

func (s *Session) Get(ctx context.Context, url string, opts ...Option) (*Response, error)

Get sends a GET request using session defaults.

func (*Session) Head

func (s *Session) Head(ctx context.Context, url string, opts ...Option) (*Response, error)

Head sends a HEAD request using session defaults.

func (*Session) Options

func (s *Session) Options(ctx context.Context, url string, opts ...Option) (*Response, error)

Options sends an OPTIONS request using session defaults.

func (*Session) Patch

func (s *Session) Patch(ctx context.Context, url string, opts ...Option) (*Response, error)

Patch sends a PATCH request using session defaults.

func (*Session) Post

func (s *Session) Post(ctx context.Context, url string, opts ...Option) (*Response, error)

Post sends a POST request using session defaults.

func (*Session) Put

func (s *Session) Put(ctx context.Context, url string, opts ...Option) (*Response, error)

Put sends a PUT request using session defaults.

type StatusError

type StatusError struct {
	StatusCode int
	Response   *Response
}

StatusError is returned for non-2xx responses.

func (*StatusError) Error

func (e *StatusError) Error() string

func (*StatusError) Unwrap

func (e *StatusError) Unwrap() error

Jump to

Keyboard shortcuts

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