httputil

package module
v0.0.0-...-a57997e Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2024 License: Apache-2.0 Imports: 12 Imported by: 0

README

httputil

http util for restful request: get, post, put, patch, delete

Usage

go get -u github.com/chinaran/httputil

Req/Resp Data

request and response data support: string, []byte, map, struct

Options (WithFunc)

http request options

WithClient

default: &http.Client{}

example: client with https

tr := &http.Transport{
	MaxIdleConns:          100,
	IdleConnTimeout:       90 * time.Second,
	TLSHandshakeTimeout:   10 * time.Second,
	ExpectContinueTimeout: 1 * time.Second,
	TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, //nolint:gosec
}
client := &http.Client{Transport: tr}
WithTimeout

default: 30 * time.Second

WithHeader

default: "Accept": "application/json", "Content-Type": "application/json;charset=UTF-8"

WithMarshal

default: json.Marshal

WithUnmarshal

default: json.Unmarshal

WithLogTimeCost

default: donot log request time cost, using logger.Printf

log style: gin

example: INFO 2021/05/04 12:24:04 REQUEST | 200 | 305.549239ms | GET https://httpbin.org/get?hello=world

WithStatusCodeJudge

default: defaultCodeJudger (2xx is the right status code)

Example

package main

import (
	"context"
	"log"

	hu "github.com/chinaran/httputil"
)

func main() {
	// get
	urlGet := "https://httpbin.org/get?hello=world"
	respGetM := map[string]interface{}{}
	if err := hu.Get(context.TODO(), urlGet, &respGetM, hu.WithLogTimeCost()); err != nil {
		log.Printf("Get %s err: %s", urlGet, err)
		return
	}
	log.Printf("Get %s map response: %+v", urlGet, respGetM)
	respGetStr := ""
	if err := hu.Get(context.TODO(), urlGet, &respGetStr, hu.WithLogTimeCost()); err != nil {
		log.Printf("Get %s err: %s", urlGet, err)
		return
	}
	log.Printf("Get %s string response: %+v", urlGet, respGetStr)

	// post
	urlPost := "https://httpbin.org/post"
	req := map[string]string{"hello": "world"}
	respPost := struct {
		Data string `json:"data"`
	}{}
	if err := hu.Post(context.TODO(), urlPost, &req, &respPost, hu.WithLogTimeCost()); err != nil {
		log.Printf("Post %s err: %s", urlPost, err)
		return
	}
	log.Printf("Post %s struct response: %+v", urlPost, respPost)
}

result:

result

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CurlLikeDumpRequest

func CurlLikeDumpRequest(req *http.Request)

func CurlLikeDumpResponse

func CurlLikeDumpResponse(resp *http.Response)

func Delete

func Delete(ctx context.Context, url string, resp interface{}, opts ...ReqOptionFunc) error

Delete http request

func Get

func Get(ctx context.Context, url string, resp interface{}, opts ...ReqOptionFunc) error

Get http request

func GetErrorCode

func GetErrorCode(err error) (int, bool)

GetErrorCode get http request's status code

func GetErrorMessage

func GetErrorMessage(err error) string

GetErrorMessage get http request's error message

func HttpRequest

func HttpRequest(ctx context.Context, method, addr string, req, resp interface{}, opts ...ReqOptionFunc) error

http request req, resp are point type

func IsErrorCode

func IsErrorCode(err error, code int) bool

IsErrorCode juede http request's stauts code

func NewRequestError

func NewRequestError(statusCode int, message string) error

NewRequestError new httputil error

func Patch

func Patch(ctx context.Context, url string, req, resp interface{}, opts ...ReqOptionFunc) error

Patch http request

func Post

func Post(ctx context.Context, url string, req, resp interface{}, opts ...ReqOptionFunc) error

Post http request

func Put

func Put(ctx context.Context, url string, req, resp interface{}, opts ...ReqOptionFunc) error

Put http request

Types

type MarshalFunc

type MarshalFunc func(v interface{}) ([]byte, error)

MarshalFunc marshal request function

type PrintfFunc

type PrintfFunc func(format string, v ...interface{})

PrintfFunc for print request log

type ReqOptionFunc

type ReqOptionFunc func(opt *reqOptions) error

ReqOptionFunc request option function

func StoreStatusCode

func StoreStatusCode(statusCode *int) ReqOptionFunc

StoreStatusCode default: not store, just judge

func WithClient

func WithClient(client *http.Client) ReqOptionFunc

WithClient default: &http.Client{}

func WithDumpRequest

func WithDumpRequest(dumpRequest, dumpResponse bool) ReqOptionFunc

WithDumpRequest default: false, false

func WithHeader

func WithHeader(header map[string]string) ReqOptionFunc

WithHeader default: "Accept": "application/json", "Content-Type": "application/json;charset=UTF-8"

func WithLogTimeCost

func WithLogTimeCost(printfer ...PrintfFunc) ReqOptionFunc

WithLogTimeCost default: false, logger.Printf

func WithMarshal

func WithMarshal(marshaler MarshalFunc) ReqOptionFunc

WithMarshal default: json.Marshal

func WithStatusCodeJudge

func WithStatusCodeJudge(codeJudger StatusCodeJudgeFunc) ReqOptionFunc

WithStatusCodeJudge default: defaultCodeJudger

func WithTimeout

func WithTimeout(timeout time.Duration) ReqOptionFunc

WithTimeout default: 30 * time.Second

func WithTraceHeaders

func WithTraceHeaders(headers http.Header) ReqOptionFunc

WithTraceHeaders append trace headers NOTE: 1. This should only be used in the demo project. 2. If the WithHeader method is used, it should be used after it.

func WithUnmarshal

func WithUnmarshal(unmarshaler UnmarshalFunc) ReqOptionFunc

WithUnmarshal default: json.Unmarshal

type RequestError

type RequestError struct {
	// http status code
	Code int
	// error message
	Message string
}

RequestError httputil request error

func (*RequestError) Error

func (e *RequestError) Error() string

type StatusCodeJudgeFunc

type StatusCodeJudgeFunc func(statusCode int) bool

StatusCodeJudgeFunc for judge status code (right status code return true)

type UnmarshalFunc

type UnmarshalFunc func(data []byte, v interface{}) error

UnmarshalFunc unmarshal response function

Jump to

Keyboard shortcuts

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