httpreq

package
v0.6.15 Latest Latest
Warning

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

Go to latest
Published: Jan 4, 2024 License: MIT Imports: 15 Imported by: 3

README

HTTP Request

httpreq provide an simple http requester and some useful util functions.

  • provide a simple and useful HTTP request client
  • provide some useful http utils functions

Install

go get github.com/gookit/goutil/netutil/httpreq

Go docs

Usage

package main

import (
	"fmt"

	"github.com/gookit/goutil/netutil/httpreq"
)

func main() {
	// Send a GET request
	resp, err := httpreq.Get("http://httpbin.org/get")
	fmt.Println(httpreq.ResponseToString(resp), err)

	// Send a POST request
	resp, err = httpreq.Post("http://httpbin.org/post", `{"name":"inhere"}`, httpreq.WithJSONType)
	fmt.Println(httpreq.ResponseToString(resp), err)
}

HTTP Client

package main

import (
    "fmt"

    "github.com/gookit/goutil/netutil/httpreq"
)

func main() {
    // create a client
    client := httpreq.New("http://httpbin.org")

    // Send a GET request
    resp, err := client.Get("/get")
    fmt.Println(httpreq.ResponseToString(resp), err)

    // Send a POST request
    resp, err = client.Post("/post", `{"name":"inhere"}`, httpreq.WithJSONType)
    fmt.Println(httpreq.ResponseToString(resp), err)
}

Package docs


func AddHeaderMap(req *http.Request, headerMap map[string]string)
func AddHeaders(req *http.Request, header http.Header)
func AppendQueryToURL(reqURL *url.URL, uv url.Values) error
func AppendQueryToURLString(urlStr string, query url.Values) string
func BuildBasicAuth(username, password string) string
func Config(fn func(hc *http.Client))
func Delete(url string, optFns ...OptionFn) (*http.Response, error)
func Get(url string, optFns ...OptionFn) (*http.Response, error)
func HeaderToString(h http.Header) string
func HeaderToStringMap(rh http.Header) map[string]string
func IsClientError(statusCode int) bool
func IsForbidden(statusCode int) bool
func IsNoBodyMethod(method string) bool
func IsNotFound(statusCode int) bool
func IsOK(statusCode int) bool
func IsRedirect(statusCode int) bool
func IsServerError(statusCode int) bool
func IsSuccessful(statusCode int) bool
func MakeBody(data any, cType string) io.Reader
func MakeQuery(data any) url.Values
func MustResp(r *http.Response, err error) *http.Response
func MustSend(method, url string, optFns ...OptionFn) *http.Response
func Post(url string, data any, optFns ...OptionFn) (*http.Response, error)
func Put(url string, data any, optFns ...OptionFn) (*http.Response, error)
func RequestToString(r *http.Request) string
func ResponseToString(w *http.Response) string
func Send(method, url string, optFns ...OptionFn) (*http.Response, error)
func SendRequest(req *http.Request, opt *Option) (*http.Response, error)
func SetTimeout(ms int)
func ToQueryValues(data any) url.Values
func ToRequestBody(data any, cType string) io.Reader
func WithJSONType(opt *Option)
type AfterSendFn func(resp *http.Response, err error)
type BasicAuthConf struct{ ... }
type Client struct{ ... }
    func New(baseURL ...string) *Client
    func NewClient(timeout int) *Client
    func NewWithDoer(d Doer) *Client
    func Std() *Client
type Option struct{ ... }
    func MakeOpt(opt *Option) *Option
    func NewOpt(fns ...OptionFn) *Option
    func NewOption(fns []OptionFn) *Option
type OptionFn func(opt *Option)
    func WithData(data any) OptionFn
type RespX struct{ ... }
    func MustRespX(r *http.Response, err error) *RespX
    func NewResp(hr *http.Response) *RespX

Testings

go test -v ./netutil/httpreq/...

Test limit by regexp:

go test -v -run ^TestSetByKeys ./netutil/httpreq/...

Documentation

Overview

Package httpreq provide an simple http requester and some useful util functions.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddHeaderMap added in v0.6.8

func AddHeaderMap(req *http.Request, headerMap map[string]string)

AddHeaderMap to reqeust instance.

func AddHeaders added in v0.5.12

func AddHeaders(req *http.Request, header http.Header)

AddHeaders adds the key, value pairs from the given http.Header to the request. Values for existing keys are appended to the keys values.

func AppendQueryToURL added in v0.6.8

func AppendQueryToURL(reqURL *url.URL, uv url.Values) error

AppendQueryToURL appends the given query string to the given url.

func AppendQueryToURLString added in v0.6.8

func AppendQueryToURLString(urlStr string, query url.Values) string

AppendQueryToURLString appends the given query data to the given url.

func BuildBasicAuth

func BuildBasicAuth(username, password string) string

BuildBasicAuth returns the base64 encoded username:password for basic auth. Then set to header "Authorization".

copied from net/http.

func Config added in v0.6.10

func Config(fn func(hc *http.Client))

Config std http client

func Delete added in v0.6.10

func Delete(url string, optFns ...OptionFn) (*http.Response, error)

Delete quick send a DELETE request by default client

func Get added in v0.6.0

func Get(url string, optFns ...OptionFn) (*http.Response, error)

Get quick send a GET request by default client

func HeaderToString added in v0.6.8

func HeaderToString(h http.Header) string

HeaderToString convert http Header to string

func HeaderToStringMap added in v0.6.0

func HeaderToStringMap(rh http.Header) map[string]string

HeaderToStringMap convert

func IsClientError

func IsClientError(statusCode int) bool

IsClientError check response is client error (400 - 500)

func IsForbidden

func IsForbidden(statusCode int) bool

IsForbidden is this response forbidden(403)

func IsNoBodyMethod added in v0.6.8

func IsNoBodyMethod(method string) bool

IsNoBodyMethod check

func IsNotFound

func IsNotFound(statusCode int) bool

IsNotFound is this response not found(404)

func IsOK

func IsOK(statusCode int) bool

IsOK check response status code is 200

func IsRedirect

func IsRedirect(statusCode int) bool

IsRedirect check response status code is in [301, 302, 303, 307]

func IsServerError

func IsServerError(statusCode int) bool

IsServerError check response is server error (500 - 600)

func IsSuccessful

func IsSuccessful(statusCode int) bool

IsSuccessful check response status code is in 200 - 300

func MakeBody added in v0.6.10

func MakeBody(data any, cType string) io.Reader

MakeBody make request body, convert data to io.Reader

func MakeQuery added in v0.6.10

func MakeQuery(data any) url.Values

MakeQuery make query string, convert data to url.Values

func MergeURLValues added in v0.6.11

func MergeURLValues(uv url.Values, values ...any) url.Values

MergeURLValues merge url.Values by overwrite.

values support: url.Values, map[string]string, map[string][]string

func MustResp added in v0.6.10

func MustResp(r *http.Response, err error) *http.Response

MustResp check error and return response

func MustSend added in v0.6.10

func MustSend(method, url string, optFns ...OptionFn) *http.Response

MustSend quick send a request by default client

func ParseAccept added in v0.6.11

func ParseAccept(acceptHeader string) []string

ParseAccept header to strings. referred from gin framework

func Post added in v0.6.0

func Post(url string, data any, optFns ...OptionFn) (*http.Response, error)

Post quick send a POST request by default client

func PostJSON added in v0.6.11

func PostJSON(url string, data any, optFns ...OptionFn) (*http.Response, error)

PostJSON quick send a POST request by default client, with JSON content type

func Put added in v0.6.10

func Put(url string, data any, optFns ...OptionFn) (*http.Response, error)

Put quick send a PUT request by default client

func RequestToString added in v0.4.5

func RequestToString(r *http.Request) string

RequestToString convert http Request to string

func ResponseToString added in v0.4.5

func ResponseToString(w *http.Response) string

ResponseToString convert http Response to string

func Send added in v0.6.10

func Send(method, url string, optFns ...OptionFn) (*http.Response, error)

Send quick send a request by default client

func SendRequest added in v0.6.10

func SendRequest(req *http.Request, opt *Option) (*http.Response, error)

SendRequest quick send a request by default client

func SetHeaderMap added in v0.6.11

func SetHeaderMap(req *http.Request, headerMap map[string]string)

SetHeaderMap to reqeust instance.

func SetHeaders added in v0.6.11

func SetHeaders(req *http.Request, headers ...http.Header)

SetHeaders sets the key, value pairs from the given http.Header to the request. Values for existing keys are overwritten.

func SetTimeout added in v0.6.10

func SetTimeout(ms int)

SetTimeout set default timeout(ms) for std client

Note: timeout unit is millisecond

func ToQueryValues

func ToQueryValues(data any) url.Values

ToQueryValues convert string-map or any-map to url.Values

data support:

  • url.Values
  • []byte
  • string
  • map[string][]string
  • map[string]string
  • map[string]any

func ToRequestBody added in v0.6.8

func ToRequestBody(data any, cType string) io.Reader

ToRequestBody make request body, convert data to io.Reader

Allow type for data:

  • string
  • []byte
  • map[string]string
  • map[string][]string/url.Values
  • io.Reader(eg: bytes.Buffer, strings.Reader)

func WithJSONType added in v0.6.10

func WithJSONType(opt *Option)

WithJSONType set request content type to JSON

Types

type AfterSendFn added in v0.6.10

type AfterSendFn func(resp *http.Response, err error)

AfterSendFn callback func

type BasicAuthConf added in v0.6.8

type BasicAuthConf struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

BasicAuthConf struct

func (*BasicAuthConf) IsValid added in v0.6.8

func (ba *BasicAuthConf) IsValid() bool

IsValid value

func (*BasicAuthConf) String added in v0.6.8

func (ba *BasicAuthConf) String() string

String build to auth header "Authorization".

func (*BasicAuthConf) Value added in v0.6.8

func (ba *BasicAuthConf) Value() string

Value build to auth header "Authorization".

type Client added in v0.6.10

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

Client a simple http request client.

func New

func New(baseURL ...string) *Client

New instance with base URL and use http.Client as default http client

func NewClient added in v0.6.9

func NewClient(timeout int) *Client

NewClient create a new http client and cache it.

Note: timeout unit is millisecond

func NewWithDoer added in v0.6.10

func NewWithDoer(d Doer) *Client

NewWithDoer instance with custom http client

func NewWithTimeout added in v0.6.11

func NewWithTimeout(ms int) *Client

NewWithTimeout new instance use http.Client and with custom timeout(ms)

func Std added in v0.6.8

func Std() *Client

Std instance

func (*Client) AnyBody added in v0.6.10

func (h *Client) AnyBody(data any) *Option

AnyBody with custom body.

Allow type:

  • string, []byte, map[string][]string/url.Values, io.Reader(eg: bytes.Buffer, strings.Reader)

func (*Client) BaseURL added in v0.6.10

func (h *Client) BaseURL(baseURL string) *Client

BaseURL set request base URL

func (*Client) BytesBody added in v0.6.10

func (h *Client) BytesBody(bs []byte) *Option

BytesBody with custom bytes body

func (*Client) ContentType added in v0.6.10

func (h *Client) ContentType(cType string) *Client

ContentType set default content-Type header.

func (*Client) DefaultHeader added in v0.6.10

func (h *Client) DefaultHeader(key, val string) *Client

DefaultHeader set default header for all requests

func (*Client) DefaultHeaderMap added in v0.6.10

func (h *Client) DefaultHeaderMap(kvMap map[string]string) *Client

DefaultHeaderMap set default headers for all requests

func (*Client) DefaultMethod added in v0.6.10

func (h *Client) DefaultMethod(method string) *Client

DefaultMethod set default request method

func (*Client) Delete added in v0.6.10

func (h *Client) Delete(url string, optFns ...OptionFn) (*http.Response, error)

Delete send DELETE request with options, return http response

func (*Client) Doer added in v0.6.10

func (h *Client) Doer() Doer

Doer get the http client

func (*Client) FormBody added in v0.6.10

func (h *Client) FormBody(data any) *Option

FormBody with custom form data body

func (*Client) Get added in v0.6.10

func (h *Client) Get(url string, optFns ...OptionFn) (*http.Response, error)

Get send GET request with options, return http response

func (*Client) JSONBody added in v0.6.10

func (h *Client) JSONBody(data any) *Option

JSONBody with custom JSON data body

func (*Client) JSONBytesBody added in v0.6.10

func (h *Client) JSONBytesBody(bs []byte) *Option

JSONBytesBody with custom bytes body, and set JSON content type

func (*Client) MustSend added in v0.6.10

func (h *Client) MustSend(method, url string, optFns ...OptionFn) *http.Response

MustSend request, will panic on error

func (*Client) OnAfterSend added in v0.6.10

func (h *Client) OnAfterSend(fn AfterSendFn) *Client

OnAfterSend add callback after send.

func (*Client) OnBeforeSend added in v0.6.10

func (h *Client) OnBeforeSend(fn func(req *http.Request)) *Client

OnBeforeSend add callback before send.

func (*Client) Post added in v0.6.10

func (h *Client) Post(url string, data any, optFns ...OptionFn) (*http.Response, error)

Post send POST request with options, return http response

func (*Client) PostJSON added in v0.6.11

func (h *Client) PostJSON(url string, data any, optFns ...OptionFn) (*http.Response, error)

PostJSON send JSON POST request with options, return http response

func (*Client) Put added in v0.6.10

func (h *Client) Put(url string, data any, optFns ...OptionFn) (*http.Response, error)

Put send PUT request with options, return http response

func (*Client) Send added in v0.6.10

func (h *Client) Send(method, url string, optFns ...OptionFn) (*http.Response, error)

Send request with option func, return http response

func (*Client) SendRequest added in v0.6.10

func (h *Client) SendRequest(req *http.Request, opt *Option) (*http.Response, error)

SendRequest send request and return http response

func (*Client) SendWithOpt added in v0.6.10

func (h *Client) SendWithOpt(url string, opt *Option) (*http.Response, error)

SendWithOpt request and return http response

func (*Client) SetClient added in v0.6.11

func (h *Client) SetClient(c Doer) *Client

SetClient custom set http client doer

func (*Client) SetTimeout added in v0.6.11

func (h *Client) SetTimeout(ms int) *Client

SetTimeout set default timeout for http client doer

func (*Client) StringBody added in v0.6.10

func (h *Client) StringBody(s string) *Option

StringBody with custom string body

func (*Client) WithBody added in v0.6.10

func (h *Client) WithBody(r io.Reader) *Option

WithBody with custom body

func (*Client) WithData added in v0.6.10

func (h *Client) WithData(data any) *Option

WithData with custom request data

func (*Client) WithOption added in v0.6.10

func (h *Client) WithOption(optFns ...OptionFn) *Option

WithOption with custom request options

type Doer

type Doer interface {
	Do(req *http.Request) (*http.Response, error)
}

Doer interface for http client.

type DoerFunc

type DoerFunc func(req *http.Request) (*http.Response, error)

DoerFunc implements the Doer

func (DoerFunc) Do

func (do DoerFunc) Do(req *http.Request) (*http.Response, error)

Do send request and return response.

type Option added in v0.6.9

type Option struct {

	// Timeout for request. unit: ms
	Timeout int
	// Method for request
	Method string
	// HeaderMap data. eg: traceid
	HeaderMap map[string]string
	// ContentType header
	ContentType string

	// Logger for request
	Logger ReqLogger
	// Context for request
	Context context.Context

	// Data for request. can be used on any request method.
	//
	// type allow:
	// 	string, []byte, io.Reader, map[string]string, ...
	Data any
	// Body data for request. used on POST, PUT, PATCH method.
	//
	// eg: strings.NewReader("name=inhere")
	Body io.Reader
	// contains filtered or unexported fields
}

Option struct

func NewOpt added in v0.6.9

func NewOpt(fns ...OptionFn) *Option

NewOpt create a new Option and with option func

func NewOption added in v0.6.10

func NewOption(fns []OptionFn) *Option

NewOption create a new Option and set option func

func OptOrNew added in v0.6.11

func OptOrNew(opt *Option) *Option

OptOrNew create a new Option if opt is nil

func (*Option) AnyBody added in v0.6.10

func (o *Option) AnyBody(data any) *Option

AnyBody with custom body.

Allow type:

  • string, []byte, map[string][]string/url.Values, io.Reader(eg: bytes.Buffer, strings.Reader)

func (*Option) BytesBody added in v0.6.10

func (o *Option) BytesBody(bs []byte) *Option

BytesBody with custom bytes body

func (*Option) Copy added in v0.6.11

func (o *Option) Copy() *Option

Copy option for new request, use for repeat send request

func (*Option) Delete added in v0.6.10

func (o *Option) Delete(url string, fns ...OptionFn) (*http.Response, error)

Delete send DELETE request and return http response

func (*Option) FormBody added in v0.6.10

func (o *Option) FormBody(data any) *Option

FormBody with custom form body data

func (*Option) Get added in v0.6.10

func (o *Option) Get(url string, fns ...OptionFn) (*http.Response, error)

Get send GET request and return http response

func (*Option) JSONBytesBody added in v0.6.10

func (o *Option) JSONBytesBody(bs []byte) *Option

JSONBytesBody with custom bytes body, and set JSON content type

func (*Option) MustSend added in v0.6.10

func (o *Option) MustSend(method, url string, fns ...OptionFn) *http.Response

MustSend request, will panic on error

func (*Option) Post added in v0.6.10

func (o *Option) Post(url string, data any, fns ...OptionFn) (*http.Response, error)

Post send POST request and return http response

func (*Option) Put added in v0.6.10

func (o *Option) Put(url string, data any, fns ...OptionFn) (*http.Response, error)

Put send PUT request and return http response

func (*Option) Send added in v0.6.10

func (o *Option) Send(method, url string, fns ...OptionFn) (*http.Response, error)

Send request and return http response

func (*Option) StringBody added in v0.6.10

func (o *Option) StringBody(s string) *Option

StringBody with custom string body

func (*Option) WithBody added in v0.6.10

func (o *Option) WithBody(r io.Reader) *Option

WithBody with custom body

func (*Option) WithClient added in v0.6.10

func (o *Option) WithClient(cli *Client) *Option

WithClient set client

func (*Option) WithContentType added in v0.6.10

func (o *Option) WithContentType(ct string) *Option

WithContentType set content type

func (*Option) WithData added in v0.6.10

func (o *Option) WithData(data any) *Option

WithData with custom data

func (*Option) WithHeader added in v0.6.10

func (o *Option) WithHeader(key, val string) *Option

WithHeader set header

func (*Option) WithHeaderMap added in v0.6.10

func (o *Option) WithHeaderMap(m map[string]string) *Option

WithHeaderMap set header map

func (*Option) WithJSON added in v0.6.10

func (o *Option) WithJSON(data any) *Option

WithJSON with custom JSON body

func (*Option) WithMethod added in v0.6.10

func (o *Option) WithMethod(method string) *Option

WithMethod set method

func (*Option) WithOptionFn added in v0.6.10

func (o *Option) WithOptionFn(fns ...OptionFn) *Option

WithOptionFn set option func

func (*Option) WithOptionFns added in v0.6.10

func (o *Option) WithOptionFns(fns []OptionFn) *Option

WithOptionFns set option func

type OptionFn added in v0.6.10

type OptionFn func(opt *Option)

OptionFn option func type

func WithData added in v0.6.10

func WithData(data any) OptionFn

WithData set request data, will auto convert to body data or query string

type Options added in v0.6.10

type Options = Option

Options alias of Option

type ReqLogger added in v0.6.0

type ReqLogger interface {
	Infof(format string, args ...any)
	Errorf(format string, args ...any)
}

ReqLogger request logger interface

type Resp added in v0.6.0

type Resp = RespX

Resp alias of RespX

type RespX added in v0.6.10

type RespX struct {
	*http.Response
	// CostTime for a request-response
	CostTime int64
}

RespX wrap http.Response and add some useful methods.

func MustRespX added in v0.6.10

func MustRespX(r *http.Response, err error) *RespX

MustRespX check error and create a new RespX instance

func NewResp added in v0.6.0

func NewResp(hr *http.Response) *RespX

NewResp instance

func WrapResp added in v0.6.11

func WrapResp(hr *http.Response, err error) (*RespX, error)

WrapResp wrap http.Response to RespX

func (*RespX) BindJSON added in v0.6.10

func (r *RespX) BindJSON(ptr any) error

BindJSON body data to a ptr, will don't check status code. if ptr is nil, will discard body data.

NOTICE: must close resp body.

func (*RespX) BindJSONOnOk added in v0.6.10

func (r *RespX) BindJSONOnOk(ptr any) error

BindJSONOnOk body data on response status is 200. if ptr is nil, will discard body data.

NOTICE: must close resp body.

func (*RespX) BodyBuffer added in v0.6.10

func (r *RespX) BodyBuffer() *bytes.Buffer

BodyBuffer read body to buffer.

NOTICE: must close resp body.

func (*RespX) BodyString added in v0.6.10

func (r *RespX) BodyString() string

BodyString get body as string.

func (*RespX) CloseBody added in v0.6.10

func (r *RespX) CloseBody() error

CloseBody close resp body

func (*RespX) ContentType added in v0.6.10

func (r *RespX) ContentType() string

ContentType get response content type

func (*RespX) IsEmptyBody added in v0.6.10

func (r *RespX) IsEmptyBody() bool

IsEmptyBody check response body is empty

func (*RespX) IsFail added in v0.6.10

func (r *RespX) IsFail() bool

IsFail check

func (*RespX) IsOk added in v0.6.10

func (r *RespX) IsOk() bool

IsOk check

func (*RespX) IsSuccessful added in v0.6.10

func (r *RespX) IsSuccessful() bool

IsSuccessful check

func (*RespX) SafeCloseBody added in v0.6.10

func (r *RespX) SafeCloseBody()

SafeCloseBody close resp body, ignore error

func (*RespX) String added in v0.6.10

func (r *RespX) String() string

BodyString get body as string.

Jump to

Keyboard shortcuts

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