reqx

package module
v0.0.0-...-99bd95b Latest Latest
Warning

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

Go to latest
Published: Mar 20, 2024 License: MIT Imports: 11 Imported by: 0

README

reqx

GoDoc

Golang http client

  • Light weight
  • Simple & Easy

Install

go get github.com/dreamph/reqx

Benchmark (reqx vs go http)

go test -bench . -benchmem -count 1

Benchmark_ReqxRequests/GET-12                      47740             22771 ns/op            1768 B/op         25 allocs/op
Benchmark_ReqxRequests/POST-12                     47290             24967 ns/op            1995 B/op         33 allocs/op
Benchmark_ReqxRequests/PUT-12                      47718             24997 ns/op            1991 B/op         33 allocs/op
Benchmark_ReqxRequests/PATCH-12                    47674             24923 ns/op            1992 B/op         33 allocs/op
Benchmark_ReqxRequests/DELETE-12                   47343             24903 ns/op            2004 B/op         33 allocs/op
Benchmark_GoHttpRequests/GET-12                    36661             31616 ns/op            5792 B/op         69 allocs/op
Benchmark_GoHttpRequests/POST-12                   34401             34127 ns/op            7456 B/op         88 allocs/op
Benchmark_GoHttpRequests/PUT-12                    34412             34492 ns/op            7389 B/op         88 allocs/op
Benchmark_GoHttpRequests/PATCH-12                  34220             34656 ns/op            7494 B/op         88 allocs/op
Benchmark_GoHttpRequests/DELETE-12                 34275             34700 ns/op            7473 B/op         88 allocs/op

Examples

package main

import (
	"bytes"
	"fmt"
	"github.com/dreamph/reqx"
	"log"
	"os"
	"time"
)

type Data struct {
	Name string `json:"name,omitempty"`
}

type Response struct {
	Origin string `json:"origin"`
}

func main() {
	clientWithBaseURL := reqx.New(
		reqx.WithBaseURL("https://httpbin.org"),
		reqx.WithTimeout(10*time.Second),
		reqx.WithHeaders(reqx.Headers{
			reqx.HeaderAuthorization: "Bearer 123456",
		}),
		reqx.WithOnBeforeRequest(func(req *reqx.RequestInfo) {
			fmt.Println(req.String())
		}),
		reqx.WithOnRequestCompleted(func(req *reqx.RequestInfo, resp *reqx.ResponseInfo) {
			fmt.Println(resp.String())
		}),
		reqx.WithOnRequestError(func(req *reqx.RequestInfo, resp *reqx.ResponseInfo) {
			fmt.Println(resp.String())
		}),
	)

	//POST
	result := &Response{}
	resp, err := clientWithBaseURL.Post(&reqx.Request{
		URL: "/post",
		Data: &Data{
			Name: "Reqx",
		},
		Headers: reqx.Headers{
			"custom": "1",
		},
		Result: result,
	})
	if err != nil {
		log.Fatalf(err.Error())
	}
	println(resp.StatusCode)
	println(result.Origin)

	client := reqx.New(
		reqx.WithTimeout(10*time.Second),
		reqx.WithHeaders(reqx.Headers{
			reqx.HeaderAuthorization: "Bearer 123456",
		}),
	)

	//POST
	result = &Response{}
	resp, err = client.Post(&reqx.Request{
		URL: "https://httpbin.org/post",
		Data: &Data{
			Name: "Reqx",
		},
		Headers: reqx.Headers{
			"custom": "1",
		},
		Result: result,
	})
	if err != nil {
		log.Fatalf(err.Error())
	}
	println(resp.StatusCode)
	println(result.Origin)

	//POST and get raw body
	var resultBytes []byte
	resp, err = client.Post(&reqx.Request{
		URL: "https://httpbin.org/post",
		Data: &Data{
			Name: "Reqx",
		},
		Result: &resultBytes,
	})
	if err != nil {
		log.Fatalf(err.Error())
	}
	println(resp.StatusCode)
	println(string(resultBytes))

	//POST with request timeout
	var resultBytes2 []byte
	resp, err = client.Post(&reqx.Request{
		URL: "https://httpbin.org/post",
		Data: &Data{
			Name: "Reqx",
		},
		Result:  &resultBytes2,
		Timeout: time.Second * 5,
	})
	if err != nil {
		log.Fatalf(err.Error())
	}
	println(resp.StatusCode)
	println(string(resultBytes2))

	//UPLOAD FILES
	test1Bytes, err := os.ReadFile("example/demo.txt")
	if err != nil {
		log.Fatalf(err.Error())
	}
	test2Bytes, err := os.ReadFile("example/demo.txt")
	if err != nil {
		log.Fatalf(err.Error())
	}
	var resultUploadBytes []byte
	resp, err = client.Post(&reqx.Request{
		URL: "https://httpbin.org/post",
		Data: &reqx.Form{
			FormData: reqx.FormData{
				"firstName": "reqx",
			},
			Files: reqx.WithFileParams(
				reqx.WithFileParam("file1", "test1.pdf", bytes.NewReader(test1Bytes)),
				reqx.WithFileParam("file2", "test2.pdf", bytes.NewReader(test2Bytes)),
			),
		},
		Result: &resultUploadBytes,
	})
	if err != nil {
		log.Fatalf(err.Error())
	}
	println(resp.StatusCode)
	println(string(resultUploadBytes))

	//GET
	result = &Response{}
	resp, err = client.Get(&reqx.Request{
		URL:    "https://httpbin.org/get",
		Result: result,
	})
	if err != nil {
		log.Fatalf(err.Error())
	}
	println(resp.StatusCode)
	println(result.Origin)

	//DELETE
	result = &Response{}
	resp, err = client.Delete(&reqx.Request{
		URL: "https://httpbin.org/delete",
		Data: &Data{
			Name: "Reqx",
		},
		Result: result,
	})
	if err != nil {
		log.Fatalf(err.Error())
	}
	println(resp.StatusCode)
	println(result.Origin)

	//PUT
	result = &Response{}
	resp, err = client.Put(&reqx.Request{
		URL: "https://httpbin.org/put",
		Data: &Data{
			Name: "Reqx",
		},
		Headers: reqx.Headers{
			"api-key": "123456",
		},
		Result: result,
	})
	if err != nil {
		log.Fatalf(err.Error())
	}
	println(resp.StatusCode)
	println(result.Origin)
}

Buy Me a Coffee

Documentation

Index

Constants

View Source
const (
	HeaderAuthorization = "Authorization"
	HeaderContentType   = "Content-Type"
)

Variables

View Source
var (
	HeaderContentTypeJson      = "application/json"
	HeaderContentTypeJsonBytes = []byte(HeaderContentTypeJson)

	HeaderContentTypeFormUrlEncoded      = "application/x-www-form-urlencoded"
	HeaderContentTypeFormUrlEncodedBytes = []byte(HeaderContentTypeFormUrlEncoded)
)

Functions

func WithFileParams

func WithFileParams(files ...FileParam) *[]FileParam

Types

type Client

type Client interface {
	Get(request *Request) (*Response, error)
	Post(request *Request) (*Response, error)
	Put(request *Request) (*Response, error)
	Delete(request *Request) (*Response, error)
	Patch(request *Request) (*Response, error)
	Head(request *Request) (*Response, error)
	Options(request *Request) (*Response, error)
}

func New

func New(opts ...ClientOptions) Client

type ClientOptions

type ClientOptions func(opts *clientOptions)

func WithBaseURL

func WithBaseURL(baseURL string) ClientOptions

func WithHeaders

func WithHeaders(headers Headers) ClientOptions

func WithJsonMarshal

func WithJsonMarshal(jsonMarshal func(v interface{}) ([]byte, error)) ClientOptions

func WithJsonUnmarshal

func WithJsonUnmarshal(jsonUnmarshal func(data []byte, v interface{}) error) ClientOptions

func WithMaxConnsPerHost

func WithMaxConnsPerHost(maxConnsPerHost int) ClientOptions

func WithOnBeforeRequest

func WithOnBeforeRequest(onBeforeRequest OnBeforeRequest) ClientOptions

func WithOnRequestCompleted

func WithOnRequestCompleted(onRequestCompleted OnRequestCompleted) ClientOptions

func WithOnRequestError

func WithOnRequestError(onRequestError OnRequestError) ClientOptions

func WithTLSConfig

func WithTLSConfig(tlsConfig *tls.Config) ClientOptions

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOptions

func WithUserAgent

func WithUserAgent(userAgent string) ClientOptions

type FileParam

type FileParam struct {
	Name     string
	FileName string
	Reader   io.Reader
}

func WithFileParam

func WithFileParam(name string, fileName string, reader io.Reader) FileParam

type Form

type Form struct {
	FormData FormData
	Files    *[]FileParam
}

type FormData

type FormData map[string]string

type FormUrlEncoded

type FormUrlEncoded struct {
	Values *url.Values
}

type Headers

type Headers map[string]string

type OnBeforeRequest

type OnBeforeRequest func(req *RequestInfo)

type OnRequestCompleted

type OnRequestCompleted func(req *RequestInfo, resp *ResponseInfo)

type OnRequestError

type OnRequestError func(req *RequestInfo, resp *ResponseInfo)

type Raw

type Raw struct {
	Body []byte
}

type Request

type Request struct {
	URL         string
	Data        interface{}
	Headers     Headers
	Result      interface{}
	ErrorResult interface{}
	Timeout     time.Duration
}

type RequestInfo

type RequestInfo struct {
	*fasthttp.Request
}

type Response

type Response struct {
	StatusCode int
}

type ResponseInfo

type ResponseInfo struct {
	*fasthttp.Response
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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