httpreq

package
v0.0.0-...-f5003fd Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2025 License: MIT Imports: 15 Imported by: 0

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/Joaolfc0/goutil/netutil/httpreq

Go docs

Usage

package main

import (
	"fmt"

	"github.com/Joaolfc0/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/Joaolfc0/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

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

AddHeaderMap to reqeust instance.

func AddHeaders

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

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

AppendQueryToURL appends the given query string to the given url.

func AppendQueryToURLString

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

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

Config std http client

func Delete

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

Delete quick send a DELETE request by default client

func Get

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

Get quick send a GET request by default client

func HeaderToString

func HeaderToString(h http.Header) string

HeaderToString convert http Header to string

func HeaderToStringMap

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

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

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

MakeBody make request body, convert data to io.Reader

func MakeQuery

func MakeQuery(data any) url.Values

MakeQuery make query string, convert data to url.Values

func MergeURLValues

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

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

MustResp check error and return response

func MustSend

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

MustSend quick send a request by default client

func ParseAccept

func ParseAccept(acceptHeader string) []string

ParseAccept header to strings. referred from gin framework

eg: acceptHeader = "application/json, text/plain, */*"

func Post

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

Post quick send a POST request by default client

func PostJSON

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

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

Put quick send a PUT request by default client

func RequestToString

func RequestToString(r *http.Request) string

RequestToString convert http Request to string

func ResponseToString

func ResponseToString(w *http.Response) string

ResponseToString convert http Response to string

func Send

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

Send quick send a request by default client

func SendRequest

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

SendRequest quick send a request by default client

func SetHeaderMap

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

SetHeaderMap to reqeust instance.

func SetHeaders

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

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

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

func WithJSONType(opt *Option)

WithJSONType set request content type to JSON

Types

type AfterSendFn

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

AfterSendFn callback func

type BasicAuthConf

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

BasicAuthConf struct

func (*BasicAuthConf) IsValid

func (ba *BasicAuthConf) IsValid() bool

IsValid value

func (*BasicAuthConf) String

func (ba *BasicAuthConf) String() string

String build to auth header "Authorization".

func (*BasicAuthConf) Value

func (ba *BasicAuthConf) Value() string

Value build to auth header "Authorization".

type Client

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

func NewClient(timeout int) *Client

NewClient create a new http client and cache it.

Note: timeout unit is millisecond

func NewWithDoer

func NewWithDoer(d Doer) *Client

NewWithDoer instance with custom http client

func NewWithTimeout

func NewWithTimeout(ms int) *Client

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

func Std

func Std() *Client

Std instance

func (*Client) AnyBody

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

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

BaseURL set request base URL

func (*Client) BytesBody

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

BytesBody with custom bytes body

func (*Client) ContentType

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

ContentType set default content-Type header.

func (*Client) DefaultHeader

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

DefaultHeader set default header for all requests

func (*Client) DefaultHeaderMap

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

DefaultHeaderMap set default headers for all requests

func (*Client) DefaultMethod

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

DefaultMethod set default request method

func (*Client) Delete

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

Delete send DELETE request with options, return http response

func (*Client) Doer

func (h *Client) Doer() Doer

Doer get the http client

func (*Client) FormBody

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

FormBody with custom form data body

func (*Client) Get

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

Get send GET request with options, return http response

func (*Client) JSONBody

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

JSONBody with custom JSON data body

func (*Client) JSONBytesBody

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

JSONBytesBody with custom bytes body, and set JSON content type

func (*Client) MustSend

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

MustSend request, will panic on error

func (*Client) OnAfterSend

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

OnAfterSend add callback after send.

func (*Client) OnBeforeSend

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

OnBeforeSend add callback before send.

func (*Client) Post

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

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

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

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

Send request with option func, return http response

func (*Client) SendRequest

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

SendRequest send request and return http response

func (*Client) SendWithOpt

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

SendWithOpt request and return http response

func (*Client) SetClient

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

SetClient custom set http client doer

func (*Client) SetTimeout

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

SetTimeout set default timeout for http client doer

func (*Client) StringBody

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

StringBody with custom string body

func (*Client) WithBody

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

WithBody with custom body

func (*Client) WithData

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

WithData with custom request data

func (*Client) WithOption

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

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

func NewOpt(fns ...OptionFn) *Option

NewOpt create a new Option and with option func

func NewOption

func NewOption(fns []OptionFn) *Option

NewOption create a new Option and set option func

func OptOrNew

func OptOrNew(opt *Option) *Option

OptOrNew create a new Option if opt is nil

func (*Option) AnyBody

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

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

BytesBody with custom bytes body

func (*Option) Copy

func (o *Option) Copy() *Option

Copy option for new request, use for repeat send request

func (*Option) Delete

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

Delete send DELETE request and return http response

func (*Option) FormBody

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

FormBody with custom form body data

func (*Option) Get

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

Get send GET request and return http response

func (*Option) JSONBytesBody

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

JSONBytesBody with custom bytes body, and set JSON content type

func (*Option) MustSend

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

MustSend request, will panic on error

func (*Option) Post

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

Post send POST request and return http response

func (*Option) Put

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

Put send PUT request and return http response

func (*Option) Send

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

Send request and return http response

func (*Option) StringBody

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

StringBody with custom string body

func (*Option) WithBody

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

WithBody with custom body

func (*Option) WithClient

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

WithClient set client

func (*Option) WithContentType

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

WithContentType set content type

func (*Option) WithData

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

WithData with custom data

func (*Option) WithHeader

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

WithHeader set header

func (*Option) WithHeaderMap

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

WithHeaderMap set header map

func (*Option) WithJSON

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

WithJSON with custom JSON body

func (*Option) WithMethod

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

WithMethod set method

func (*Option) WithOptionFn

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

WithOptionFn set option func

func (*Option) WithOptionFns

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

WithOptionFns set option func

type OptionFn

type OptionFn func(opt *Option)

OptionFn option func type

func WithData

func WithData(data any) OptionFn

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

type Options

type Options = Option

Options alias of Option

type ReqLogger

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

ReqLogger request logger interface

type Resp

type Resp = RespX

Resp alias of RespX

type RespX

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

RespX wrap http.Response and add some useful methods.

func MustRespX

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

MustRespX check error and create a new RespX instance

func NewResp

func NewResp(hr *http.Response) *RespX

NewResp instance

func WrapResp

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

WrapResp wrap http.Response to RespX

func (*RespX) BindJSON

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

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

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

BodyBuffer read body to buffer.

NOTICE: must close resp body.

func (*RespX) BodyString

func (r *RespX) BodyString() string

BodyString get body as string.

func (*RespX) CloseBody

func (r *RespX) CloseBody() error

CloseBody close resp body

func (*RespX) ContentType

func (r *RespX) ContentType() string

ContentType get response content type

func (*RespX) IsEmptyBody

func (r *RespX) IsEmptyBody() bool

IsEmptyBody check response body is empty

func (*RespX) IsFail

func (r *RespX) IsFail() bool

IsFail check

func (*RespX) IsOk

func (r *RespX) IsOk() bool

IsOk check

func (*RespX) IsSuccessful

func (r *RespX) IsSuccessful() bool

IsSuccessful check

func (*RespX) SafeCloseBody

func (r *RespX) SafeCloseBody()

SafeCloseBody close resp body, ignore error

func (*RespX) String

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