httpx

package module
v0.1.4 Latest Latest
Warning

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

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

README

gopkg/httpx

gopkg/httpx is a componentized http plugin.

It providels:

  • An easy way to configre and manage http client.
  • Custom request protocol.

Based on resty.dev/v3

Required go1.23

Contents

Install

go get github.com/wwwangxc/gopkg/httpx

⬆ back to top

Quick Start

package httpx_test

import (
	"context"

	// gopkg/httpx will automatically read configuration
	// files (./app.yaml) when package loaded
	"github.com/wwwangxc/gopkg/httpx"
)

func Example() {
	// Load config (optional)
	// gopkg/httpx will automatically read configuration
	// files (./app.yaml) when package loaded
	httpx.LoadConfig("./custom_config.yaml")

	// Create HTTP/HTTPS client with config
	cli := httpx.NewClientProxy("name")

	// Send HTTP/HTTPX GET request
	var rsp map[string]any
	_ = cli.Get(context.Background(), "https://httpbin.org/anything", &rsp)
}

⬆ back to top

Config
client:
  http: 
    header:
      User-Agent: gopkg/httpx
      Content-Type: application/json;charset=UTF-8
    transport:
      max_idle_conns: 200
      max_idle_conns_per_host: 50
      max_conns_per_host: 100
      idle_conn_timeout: 90s
      tls_handshake_timeout: 3s
      expect_continue_timeout: 1s
      response_header_timeout: 5s
      dial:
        timeout: 3s
        keep_alive: 30s
    option:
      trace: true
      debug: true
      allow_method_get_payload: true
      allow_method_delete_payload: true
  service:
    - name: http1
      dsn: https://httpbin.org
      timeout: 3s
    - name: http2
      dsn: https://httpbin1.org,https://httpbin2.org
      timeout: 1s
      header:
        User-Agent: custom_agent
        Content-Type: custom_content_type
      transport:
        max_idle_conns: 1
        max_idle_conns_per_host: 2
        max_conns_per_host: 3
        idle_conn_timeout: 1s
        tls_handshake_timeout: 2s
        expect_continue_timeout: 3s
        response_header_timeout: 4s
        dial:
          timeout: 5s
          keep_alive: 6s
      option:
        trace: false
        debug: false
        allow_method_get_payload: false
        allow_method_delete_payload: false

⬆ back to top

ClientProxy
package httpx_test

import (
	"net/http"
	"time"

	"resty.dev/v3"

	// gopkg/httpx will automatically read configuration
	// files (./app.yaml) when package loaded
	"github.com/wwwangxc/gopkg/httpx"
)

func Example() {
	// Create HTTP/HTTPS client proxy with config
	_ = httpx.NewClientProxy("name")

	// Create HTTP/HTTPX client proxy with options
	_ = httpx.NewClientProxy("name",
		httpx.C.WithHost("httpbin1.org", "httpbin2.org"),
		httpx.C.WithTimeout(3*time.Second),
		httpx.C.WithHeader(map[string]string{}),
		httpx.C.WithTransport(&http.Transport{}),
		httpx.C.WithRequestMiddlewares([]resty.RequestMiddleware{}...),
		httpx.C.WithResponseMiddlewares([]resty.ResponseMiddleware{}...),
		httpx.C.OnSuccess(func(c *resty.Client, r *resty.Response) {}),
		httpx.C.OnError(func(r *resty.Request, err error) {}),
		httpx.C.OnInvalid(func(r *resty.Request, err error) {}),
		httpx.C.OnPanic(func(r *resty.Request, err error) {}),
		httpx.C.WithAllowMethodGetPayload(),
		httpx.C.WithAllowMethodDeletePayload(),
		httpx.C.WithTrace(),
		httpx.C.WithDebug(),
	)
}

⬆ back to top

Do Request With Protocol
package httpx_test

import (
	"context"
	"fmt"
	"net/http"

	"resty.dev/v3"

	// gopkg/httpx will automatically read configuration
	// files (./app.yaml) when package loaded
	"github.com/wwwangxc/gopkg/httpx"
)

func Example() {
	// Create request protocol
	req := &MyRequest{}

	// Create HTTP/HTTPS client with config
	cli := httpx.NewClientProxy("name")

	// Send request with protocol
	var rsp map[string]any
	_ = cli.Do(context.Background(), req, &rsp)
}

// MyRequest my request protocol
//
// By implementing the appropriate Getter interface for the request protocol,
// various options in the request can be set automatically.
//
//	Support checker && getter:
//
//		- [RequestChecker]                        // check current request.
//		- [MethodGetter]                          // sets the http method
//		- [BasicAuthGetter]                       // sets the basic authentication header
//		- [BearerTokenAuthGetter]                 // sets the auth token header
//		- [CookiesGetter]                         // append cookies
//		- [HeaderGetter]                          // set multiple header fields and their values
//		- [PathParamsGetter]                      // set multiple URL path key-value pair
//		- [QueryParamsGetter]                     // set multiple parameter
//		- [QueryStringGetter]                     // set the query string
//		- [FormParamsGetter]                      // set form parameters and their values
//		- [BodyGetter]                            // set the request body
//		- [TimeoutGetter]                         // set the request timeout
//		- [RetryGetter]                           // set the retry times and conditions when the request failed
//		- [RetryWaitGetter]                       // set the default wait time for sleep before retrying
//		- [RetryHooksGetter]                      // set retry hooks
//		- [AllowResponseBodyUnlimitedReadsGetter] // enable the response body in memory that provides an ability to do unlimited reads.
//		- [AllowMethodGetPayloadGetter]           // allows the GET method with payload.
//		- [AllowMethodDeletePayloadGetter]        // allows the DELETE method with payload.
//		- [DebugGetter]                           // enable debug mode.
//		- [TraceGetter]                           // enable trace for current request.
//		- [ExpectResponseContentTypeGetter]       // set fallback `Content-Type`.
//		- [ForceResponseContentTypeGetter]        // set force response `Content-Type`.
type MyRequest struct{}

func (s *MyRequest) Host() string {
	return "https://httpbin.org"
}

func (s *MyRequest) Path() string {
	return "/anything"
}

func (s *MyRequest) Check() error {
	if s == nil {
		return fmt.Error("invalid request")
	}
	return nil
}

func (s *MyRequest) AllowResponseBodyUnlimitedReads() {}

func (s *MyRequest) AllowMethodGetPayload() {}

func (s *MyRequest) AllowMethodDeletePayload() {}

func (s *MyRequest) Method() string {
	return http.MethodGet
}

func (s *MyRequest) BasicAuth() (username string, password string) {
	return "username", "password"
}

func (s *MyRequest) BearerTokenAuth() string {
	return "token"
}

func (s *MyRequest) Cookies() []*http.Cookie {
	return []*http.Cookie{
		{Name: "cookie_1"},
		{Name: "cookie_2"},
	}
}

func (s *MyRequest) Header() map[string]string {
	return map[string]string{
		"Content-Type": "application/json",
	}
}

func (s *MyRequest) PathParams() map[string]string {
	return map[string]string{
		"key": "value",
	}
}

func (s *MyRequest) QueryParams() map[string]string {
	return map[string]string{
		"key": "value",
	}
}

func (s *MyRequest) QueryString() string {
	return "key_1=value_1&key_2=value_2"
}

func (s *MyRequest) FormParams() map[string]string {
	return map[string]string{
		"key": "value",
	}
}

func (s *MyRequest) Body() any {
	return map[string]any{
		"key": "value",
	}
}

func (s *MyRequest) Timeout() time.Duration {
	return 3 * time.Second
}

func (s *MyRequest) Retry() (retryTimes int, retryConds []resty.RetryConditionFunc) {
	return 3, []resty.RetryConditionFunc{
		func(r *resty.Response, err error) bool { return err != nil },
		func(r *resty.Response, err error) bool { return r.StatusCode() != http.StatusOK },
	}
}

func (s *MyRequest) RetryWait() time.Duration {
	return 100 * time.Millisecond
}

func (s *MyRequest) RetryHooks(ctx context.Context) []resty.RetryHookFunc {
	return []resty.RetryHookFunc{
		func(r *resty.Response, err error) { fmt.Println("retry once") },
	}
}

func (s *MyRequest) ExpectResponseContentType() string {
    return "application/json"
}

func (s *MyRequest) ForceResponseContentType() string {
    return "application/json"
}

⬆ back to top

Get
package httpx_test

import (
	"context"
	"net/http"
	"time"

	"resty.dev/v3"

	// gopkg/httpx will automatically read configuration
	// files (./app.yaml) when package loaded
	"github.com/wwwangxc/gopkg/httpx"
)

func Example() {
	// Create HTTP/HTTPS client with config
	cli := httpx.NewClientProxy("name")

	// Request supported options
	requestOpts := []httpx.RequestOption{
		httpx.R.WithBasicAuth("username", "password"),
		httpx.R.WithBearerTokenAuth("token"),
		httpx.R.WithCookies([]*http.Cookie{}...),
		httpx.R.WithHeader(map[string]string{}),
		httpx.R.WithPathParams(map[string]string{}),
		httpx.R.WithQueryParams(map[string]string{}),
		httpx.R.WithQueryString(""),
		httpx.R.WithFormParams(map[string]string{}),
		httpx.R.WithBody(map[string]any{}),
		httpx.R.WithTimeout(3 * time.Second),
		httpx.R.WithRetry(3, []resty.RetryConditionFunc{}...),
		httpx.R.WithRetryWait(100 * time.Millisecond),
		httpx.R.WithRetryHooks([]resty.RetryHookFunc{}...),
		httpx.R.AllowResponseBodyUnlimitedReads(),
		httpx.R.AllowMethodGetPayload(),
		httpx.R.AllowMethodDeletePayload(),
		httpx.R.WithExpectResponseContentType("application/json"),
		httpx.R.WithForceResponseContentType("application/json"),
		httpx.R.WithDebug(),
		httpx.R.WithTrace(),
	}

	// Send request
	var rsp map[string]any
	_ = cli.Get(context.Background(), "https://httpbin.org/anything", &rsp, requestOpts...)
}

⬆ back to top

Head
package httpx_test

import (
	"context"
	"net/http"
	"time"

	"resty.dev/v3"

	// gopkg/httpx will automatically read configuration
	// files (./app.yaml) when package loaded
	"github.com/wwwangxc/gopkg/httpx"
)

func Example() {
	// Create HTTP/HTTPS client with config
	cli := httpx.NewClientProxy("name")

	// Request supported options
	requestOpts := []httpx.RequestOption{
		...
	}

	// Send request
	var rsp map[string]any
	_ = cli.Head(context.Background(), "https://httpbin.org/anything", &rsp, requestOpts...)
}

⬆ back to top

Post
package httpx_test

import (
	"context"
	"net/http"
	"time"

	"resty.dev/v3"

	// gopkg/httpx will automatically read configuration
	// files (./app.yaml) when package loaded
	"github.com/wwwangxc/gopkg/httpx"
)

func Example() {
	// Create HTTP/HTTPS client with config
	cli := httpx.NewClientProxy("name")

	// Request supported options
	requestOpts := []httpx.RequestOption{
		...
	}

	// Send request
	var rsp map[string]any
	_ = cli.Post(context.Background(), "https://httpbin.org/anything", &rsp, requestOpts...)
}

⬆ back to top

Put
package httpx_test

import (
	"context"
	"net/http"
	"time"

	"resty.dev/v3"

	// gopkg/httpx will automatically read configuration
	// files (./app.yaml) when package loaded
	"github.com/wwwangxc/gopkg/httpx"
)

func Example() {
	// Create HTTP/HTTPS client with config
	cli := httpx.NewClientProxy("name")

	// Request supported options
	requestOpts := []httpx.RequestOption{
		...
	}

	// Send request
	var rsp map[string]any
	_ = cli.Put(context.Background(), "https://httpbin.org/anything", &rsp, requestOpts...)
}

⬆ back to top

Delete
package httpx_test

import (
	"context"
	"net/http"
	"time"

	"resty.dev/v3"

	// gopkg/httpx will automatically read configuration
	// files (./app.yaml) when package loaded
	"github.com/wwwangxc/gopkg/httpx"
)

func Example() {
	// Create HTTP/HTTPS client with config
	cli := httpx.NewClientProxy("name")

	// Request supported options
	requestOpts := []httpx.RequestOption{
		...
	}

	// Send request
	var rsp map[string]any
	_ = cli.Delete(context.Background(), "https://httpbin.org/anything", &rsp, requestOpts...)
}

⬆ back to top

Options
package httpx_test

import (
	"context"
	"net/http"
	"time"

	"resty.dev/v3"

	// gopkg/httpx will automatically read configuration
	// files (./app.yaml) when package loaded
	"github.com/wwwangxc/gopkg/httpx"
)

func Example() {
	// Create HTTP/HTTPS client with config
	cli := httpx.NewClientProxy("name")

	// Request supported options
	requestOpts := []httpx.RequestOption{
		...
	}

	// Send request
	var rsp map[string]any
	_ = cli.Options(context.Background(), "https://httpbin.org/anything", &rsp, requestOpts...)
}

⬆ back to top

Patch
package httpx_test

import (
	"context"
	"net/http"
	"time"

	"resty.dev/v3"

	// gopkg/httpx will automatically read configuration
	// files (./app.yaml) when package loaded
	"github.com/wwwangxc/gopkg/httpx"
)

func Example() {
	// Create HTTP/HTTPS client with config
	cli := httpx.NewClientProxy("name")

	// Request supported options
	requestOpts := []httpx.RequestOption{
		...
	}

	// Send request
	var rsp map[string]any
	_ = cli.Patch(context.Background(), "https://httpbin.org/anything", &rsp, requestOpts...)
}

⬆ back to top

Request Protocol
// RequestProtocol custom request protocol
//
// By implementing the appropriate Getter interface for the request protocol,
// various options in the request can be set automatically.
//
//	Support checker && getter:
//
//		- [RequestChecker]                        // check current request.
//		- [MethodGetter]                          // sets the http method
//		- [BasicAuthGetter]                       // sets the basic authentication header
//		- [BearerTokenAuthGetter]                 // sets the auth token header
//		- [CookiesGetter]                         // append cookies
//		- [HeaderGetter]                          // set multiple header fields and their values
//		- [PathParamsGetter]                      // set multiple URL path key-value pair
//		- [QueryParamsGetter]                     // set multiple parameter
//		- [QueryStringGetter]                     // set the query string
//		- [FormParamsGetter]                      // set form parameters and their values
//		- [BodyGetter]                            // set the request body
//		- [TimeoutGetter]                         // set the request timeout
//		- [RetryGetter]                           // set the retry times and conditions when the request failed
//		- [RetryWaitGetter]                       // set the default wait time for sleep before retrying
//		- [RetryHooksGetter]                      // set retry hooks
//		- [AllowResponseBodyUnlimitedReadsGetter] // enable the response body in memory that provides an ability to do unlimited reads.
//		- [AllowMethodGetPayloadGetter]           // allows the GET method with payload.
//		- [AllowMethodDeletePayloadGetter]        // allows the DELETE method with payload.
//		- [DebugGetter]                           // enable debug mode.
//		- [TraceGetter]                           // enable trace for current request.
//		- [ExpectResponseContentTypeGetter]       // set fallback `Content-Type`.
//		- [ForceResponseContentTypeGetter]        // set force response `Content-Type`.
type RequestProtocol interface {
	Host() string
	Path() string
}

⬆ back to top

RequestChecker

Implement this interface will automatically check current HTTP request.

type RequestChecker interface{ Check() error }

For example:

package main

type MyRequest struct{}

func (s *MyRequest) Check() error {
	if s == nil {
		return fmt.Error("invalid request")
	}
	return nil
}

⬆ back to top

MethodGetter

Implement this interface to set the method for current current HTTP request.

type MethodGetter interface {
	Method() string
}

For example:

package main

import (
	"net/http"
)

type MyRequest struct{}

func (s *MyRequest) Method() string {
	return http.MethodGet
}

⬆ back to top

BasicAuthGetter

Implement this interface to automatically set the Basic Authentication header in the current HTTP request.

type BasicAuthGetter interface {
	BasicAuth() (username, password string)
}

For example:

package main

type MyRequest struct{}

func (s *MyRequest) BasicAuth() (username string, password string) {
	return "username", "password"
}

⬆ back to top

BearerTokenAuthGetter

Implement this interface to automatically set the Bearer Authentication header in the current HTTP request.

type BearerTokenAuthGetter interface{ BearerTokenAuth() string }

For example:

package main

type MyRequest struct{}

func (s *MyRequest) BearerTokenAuth() string {
	return "token"
}

⬆ back to top

CookieGetters

Implement this interface to automatically append the cookies in the current HTTP request.

type CookiesGetter interface{ Cookies() []*http.Cookie }

For example:

package main

type MyRequest struct{}

func (s *MyRequest) Cookies() []*http.Cookie {
	return []*http.Cookie{
		{Name: "cookie_1"},
		{Name: "cookie_2"},
	}
}

⬆ back to top

HeaderGetter

Implement this interface to automatically set headers in the current HTTP request.

type HeaderGetter interface{ Header() map[string]string }

For example:

package main

type MyRequest struct{}

func (s *MyRequest) Header() map[string]string {
	return map[string]string{
		"Content-Type": "application/json",
	}
}

⬆ back to top

PathParamsGetter

Implement this interface to automatically set the parameters in the current HTTP request path.

type PathParamsGetter interface{ PathParams() map[string]string }

For example:

package main

type MyRequest struct{}

func (s *MyRequest) PathParams() map[string]string {
	return map[string]string{
		"key": "value",
	}
}

⬆ back to top

QueryParamsGetter

Implement this interface to automatically set the query parameters in the current HTTP request.

type QueryParamsGetter interface{ QueryParams() map[string]string }

For example:

package main

type MyRequest struct{}

func (s *MyRequest) QueryParams() map[string]string {
	return map[string]string{
		"key": "value",
	}
}

⬆ back to top

QueryStringGetter

Implement this interface to automatically set the query parameters string in the current HTTP request.

type QueryStringGetter interface{ QueryString() string }

For example:

package main

type MyRequest struct{}

func (s *MyRequest) QueryString() string {
	return "key_1=value_1&key_2=value_2"
}

⬆ back to top

FormParamsGetter

Implement this interface to automatically set the form parameters in the current HTTP request.

type FormParamsGetter interface{ FormParams() map[string]string }

For example:

package main

type MyRequest struct{}

func (s *MyRequest) FormParams() map[string]string {
	return map[string]string{
		"key": "value",
	}
}

⬆ back to top

BodyGetter

Implement this interface to automatically set the body in the current HTTP request.

type BodyGetter interface{ Body() any }

For example:

package main

type MyRequest struct{}

func (s *MyRequest) Body() any {
	return map[string]any{
		"key": "value",
	}
}

⬆ back to top

TimeoutGetter

Implement this interface to automatically set the timeout for current HTTP request.

type TimeoutGetter interface{ Timeout() time.Duration }

For example:

package main

type MyRequest struct{}

func (s *MyRequest) Timeout() time.Duration {
	return 3 * time.Second
}

⬆ back to top

RetryGetter

Implement this interface to automatically set the retry strategy for current HTTP request.

type RetryGetter interface {
	Retry() (retryTimes int, retryConds []resty.RetryConditionFunc)
}

For example:

package main

type MyRequest struct{}

func (s *MyRequest) Retry() (retryTimes int, retryConds []resty.RetryConditionFunc) {
	return 3, []resty.RetryConditionFunc{
		func(r *resty.Response, err error) bool { return err != nil },
		func(r *resty.Response, err error) bool { return r.StatusCode() != http.StatusOK },
	}
}

⬆ back to top

RetryWaitGetter

Implement this interface to automatically set the wait time before retry sleep for current HTTP request.

type RetryWaitGetter interface{ RetryWait() time.Duration }

For example:

package main

type MyRequest struct{}

func (s *MyRequest) RetryWait() time.Duration {
	return 100 * time.Millisecond
}

⬆ back to top

RetryHooksGetter

Implement this interface to automatically set the retry hooks for current HTTP request.

type RetryHooksGetter interface {
	RetryHooks(ctx context.Context) []resty.RetryHookFunc
}

For example:

package main

type MyRequest struct{}

func (s *MyRequest) RetryHooks(ctx context.Context) []resty.RetryHookFunc {
	return []resty.RetryHookFunc{
		func(r *resty.Response, err error) { fmt.Println("retry once") },
	}
}

⬆ back to top

AllowResponseBodyUnlimitedReadsGetter

Implement this interface for enable the response body in memory that provides an ability to do unlimited reads.

[!WARNING] Use with case Turning on this feature keeps the response body in memory, which might cause additional memory usage.

type AllowResponseBodyUnlimitedReadsGetter interface{ AllowResponseBodyUnlimitedReads() }

For example:

package main

type MyRequest struct{}

func (s *MyRequest) AllowResponseBodyUnlimitedReads() {}

⬆ back to top

AllowMethodGetPayloadGetter

Implement this interface will allows the GET method with payload on the Resty client.

type AllowMethodGetPayloadGetter interface{ AllowMethodGetPayload() }

For example:

package main

type MyRequest struct{}

func (s *MyRequest) AllowMethodGetPayload() {}

⬆ back to top

AllowMethodDeletePayloadGetter

Implement this interface will allows the DELETE method with payload on the Resty client.

type AllowMethodDeletePayloadGetter interface{ AllowMethodDeletePayload() }

For example:

package main

type MyRequest struct{}

func (s *MyRequest) AllowMethodDeletePayload() {}

⬆ back to top

DebugGetter

Implement this interface will enables the debug mode on the current request. It logs the details current request and response.

type DebugGetter interface{ Debug() }

For example:

package main

type MyRequest struct{}

func (s *MyRequest) Debug() {}

⬆ back to top

TraceGetter

Implement this interface will enables trace for the current request.

type TraceGetter interface{ Trace() }

For example:

package main

type MyRequest struct{}

func (s *MyRequest) Trace() {}

⬆ back to top

ExpectResponseContentTypeGetter

Implement this interface to automatically set the fallback Content-Type for automatic unmarshalling when the Content-Type response header is unavailable.

type ExpectResponseContentTypeGetter interface{ ExpectResponseContentType() string }

For example:

package main

type MyRequest struct{}

func (s *MyRequest) ExpectResponseContentType() string {
    return "application/json"
}

⬆ back to top

ForceResponseContentTypeGetter

Implement this interface to automatically set the force response Content-Type for the current HTTP request.

type ForceResponseContentTypeGetter interface{ ForceResponseContentType() string }

For example:

package main

type MyRequest struct{}

func (s *MyRequest) ForceResponseContentType() string {
    return "application/json"
}

⬆ back to top

How To Mock

package httpx_test

import (
	"testing"

	"github.com/agiledragon/gomonkey/v2"
	"go.uber.org/mock/gomock"

	"github.com/wwwangxc/gopkg/httpx"
	"github.com/wwwangxc/gopkg/httpx/mockhttpx"
)

func TestNewClientProxy(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	// Mock client proxy
	mockedCli := mockhttpx.NewMockClientProxy(ctrl)
	mockedCli.EXPECT().Do(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes()
	mockedCli.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes()
	mockedCli.EXPECT().Head(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes()
	mockedCli.EXPECT().Post(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes()
	mockedCli.EXPECT().Put(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes()
	mockedCli.EXPECT().Delete(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes()
	mockedCli.EXPECT().Options(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes()
	mockedCli.EXPECT().Patch(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes()

	// Mock function httpx.NewClientProxy
	patches := gomonkey.ApplyFunc(httpx.NewClientProxy,
		func(string, ...httpx.ClientOption) httpx.ClientProxy {
			return mockedCli
		})
	defer patches.Reset()

	// dosomething...
}

⬆ back to top

Documentation

Overview

Package gopkg/httpx is a componentized http plugin.

It provides an easy way to configre and manage http client.

Based on https://resty.dev/

Example
package main

import (
	"context"

	"github.com/wwwangxc/gopkg/httpx"
)

func main() {
	// Load config (optional)
	// gopkg/httpx will automatically read configuration
	// files (./app.yaml) when package loaded
	httpx.LoadConfig("./custom_config.yaml")

	// Create HTTP/HTTPS client with config
	cli := httpx.NewClientProxy("name")

	// Send HTTP/HTTPX GET request
	var rsp map[string]any
	_ = cli.Get(context.Background(), "https://httpbin.org/anything", &rsp)
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var C = (*clientOption)(nil)

C is the client proxy option provider

View Source
var R = (*requestOption)(nil)

R is the request option provider

Functions

func LoadConfig

func LoadConfig(path string) error

LoadConfig load config from file

Types

type AllowMethodDeletePayloadGetter

type AllowMethodDeletePayloadGetter interface{ AllowMethodDeletePayload() }

AllowMethodDeletePayloadGetter return nothing

Implement this interface will allows the DELETE method with payload on the Resty client.

Usage Example:

type MyRequest struct{}

func (s *MyRequest) AllowMethodDeletePayloadGetter() {}

type AllowMethodGetPayloadGetter

type AllowMethodGetPayloadGetter interface{ AllowMethodGetPayload() }

AllowMethodGetPayloadGetter return nothing

Implement this interface will allows the GET method with payload on the Resty client.

Usage Example:

type MyRequest struct{}

func (s *MyRequest) AllowMethodGetPayloadGetter() {}

type AllowResponseBodyUnlimitedReadsGetter

type AllowResponseBodyUnlimitedReadsGetter interface{ AllowResponseBodyUnlimitedReads() }

AllowResponseBodyUnlimitedReadsGetter return nothing

Implement this interface for enable the response body in memory that provides an ability to do unlimited reads.

Usage Example:

type MyRequest struct{}

func (s *MyRequest) AllowResponseBodyUnlimitedReadsGetter() {}

Unlimited reads are possible in a few scenarios, even without enabling it.

  • When debug mode is enabled

NOTE: Use with care

  • Turning on this feature keeps the response body in memory, which might cause additional memory usage.

type BasicAuthGetter

type BasicAuthGetter interface {
	BasicAuth() (username, password string)
}

BasicAuth returns username & password in basic authentication

Implement this interface to automatically set the Basic Authentication header in the current HTTP request.

Header Format:

Authorization: Basic <base64-encoded-value>

Usage Example:

type MyRequest struct{}

func (s *MyRequest) BasicAuth() (username, password string) {
	return "username", "password"
}

type BearerTokenAuthGetter

type BearerTokenAuthGetter interface{ BearerTokenAuth() string }

BearerTokenAuthGetter returns authentication token

Implement this interface to automatically set the Bearer Authentication header in the current HTTP request.

Header Format:

Authorization: Bearer <token>

Usage Example:

type MyRequest struct{}

func (s *MyRequest) BearerTokenAuth() string {
	return "token"
}

type BodyGetter

type BodyGetter interface{ Body() any }

BodyGetter returns the body in the current request

Implement this interface to automatically set the body in the current HTTP request.

Usage Example:

type MyRequest struct{}

func (s *MyRequest) Body() any {
	// support string
	return `{"params": "value"}`

	// support []byte
	return []byte("This is my raw request")

	// support map
	return map[string]any {
		"params": "value",
	}

	// support struct
	return Request {
		Params: "value",
	}
}

type ClientOption

type ClientOption func(*resty.Client)

ClientOption client proxy option

type ClientProxy

type ClientProxy interface {
	// Do http request by protocol
	Do(ctx context.Context, req RequestProtocol, dest any) error

	// Get will do http GET request
	//
	// URL format such as:
	//	          Normal: http://127.0.0.1:8080/v1/users/details
	//	With path params: http://127.0.0.1:8080/v1/users/{user_id}/repo/{repo_id}/star
	Get(ctx context.Context, url string, dest any, opts ...RequestOption) error

	// Head will do http HEAD request
	//
	// URL format such as:
	// 	          Normal: http://127.0.0.1:8080/v1/users/details
	// 	With path params: http://127.0.0.1:8080/v1/users/{user_id}/repo/{repo_id}/star
	Head(ctx context.Context, url string, dest any, opts ...RequestOption) error

	// Post will do http POST request
	//
	// URL format such as:
	// 	          Normal: http://127.0.0.1:8080/v1/users/details
	// 	With path params: http://127.0.0.1:8080/v1/users/{user_id}/repo/{repo_id}/star
	Post(ctx context.Context, url string, dest any, opts ...RequestOption) error

	// Put will do http PUT request
	//
	// URL format such as:
	// 	          Normal: http://127.0.0.1:8080/v1/users/details
	// 	With path params: http://127.0.0.1:8080/v1/users/{user_id}/repo/{repo_id}/star
	Put(ctx context.Context, url string, dest any, opts ...RequestOption) error

	// Delete will do http DELETE request
	//
	// URL format such as:
	// 	          Normal: http://127.0.0.1:8080/v1/users/details
	// 	With path params: http://127.0.0.1:8080/v1/users/{user_id}/repo/{repo_id}/star
	Delete(ctx context.Context, url string, dest any, opts ...RequestOption) error

	// Options will do http OPTIONS request
	//
	// URL format such as:
	// 	          Normal: http://127.0.0.1:8080/v1/users/details
	// 	With path params: http://127.0.0.1:8080/v1/users/{user_id}/repo/{repo_id}/star
	Options(ctx context.Context, url string, dest any, opts ...RequestOption) error

	// Patch will do http PATCH request
	//
	// URL format such as:
	// 	          Normal: http://127.0.0.1:8080/v1/users/details
	// 	With path params: http://127.0.0.1:8080/v1/users/{user_id}/repo/{repo_id}/star
	Patch(ctx context.Context, url string, dest any, opts ...RequestOption) error
}

ClientProxy http client proxy

func NewClientProxy

func NewClientProxy(name string, opt ...ClientOption) ClientProxy

NewClientProxy new http client proxy

Example
package main

import (
	"net/http"
	"time"

	"resty.dev/v3"

	"github.com/wwwangxc/gopkg/httpx"
)

func main() {
	// Create HTTP/HTTPS client proxy with config
	_ = httpx.NewClientProxy("name")

	// Create HTTP/HTTPX client proxy with options
	_ = httpx.NewClientProxy("name",
		httpx.C.WithHost("httpbin1.org", "httpbin2.org"),
		httpx.C.WithTimeout(3*time.Second),
		httpx.C.WithHeader(map[string]string{}),
		httpx.C.WithTransport(&http.Transport{}),
		httpx.C.WithRequestMiddlewares([]resty.RequestMiddleware{}...),
		httpx.C.WithResponseMiddlewares([]resty.ResponseMiddleware{}...),
		httpx.C.OnSuccess(func(c *resty.Client, r *resty.Response) {}),
		httpx.C.OnError(func(r *resty.Request, err error) {}),
		httpx.C.OnInvalid(func(r *resty.Request, err error) {}),
		httpx.C.OnPanic(func(r *resty.Request, err error) {}),
		httpx.C.WithAllowMethodGetPayload(),
		httpx.C.WithAllowMethodDeletePayload(),
		httpx.C.WithTrace(),
		httpx.C.WithDebug(),
	)
}

type CookiesGetter

type CookiesGetter interface{ Cookies() []*http.Cookie }

CookieGetters returns the cookies of the current request

Implement this interface to automatically append the cookies in the current HTTP request.

Usage Example:

type MyRequest struct{}

func (s *MyRequest) Cookies() []*http.Cookie {
	return []*http.Cookie{}
}

type DebugGetter added in v0.1.2

type DebugGetter interface{ Debug() }

DebugGetter return nothing

Implement this interface will enables the debug mode on the current request. It logs the details current request and response.

Usage Example:

type MyRequest struct{}

func (s *MyRequest) Debug() {}

type ExpectResponseContentTypeGetter added in v0.1.3

type ExpectResponseContentTypeGetter interface{ ExpectResponseContentType() string }

ExpectResponseContentTypeGetter returns fallback `Content-Type`

Implement this interface to automatically set the fallback `Content-Type` for automatic unmarshalling when the `Content-Type` response header is unavailable.

Usage Example:

type MyRequest struct{}

func (s *MyRequest) ExpectResponseContentType() string {
	return "application/json"
}

type ForceResponseContentTypeGetter added in v0.1.3

type ForceResponseContentTypeGetter interface{ ForceResponseContentType() string }

ForceResponseContentTypeGetter returns force `Content-Type`

Implement this interface to automatically set the force response `Content-Type` for the current HTTP request.

Usage Example:

type MyRequest struct{}

func (s *MyRequest) ForceResponseContentType() string {
	return "application/json"
}

type FormParamsGetter

type FormParamsGetter interface{ FormParams() map[string]string }

FormParamsGetter returns the form parameters in the current request

Implement this interface to automatically set the form parameters in the current HTTP request.

Usage Example:

type MyRequest struct{}

func (s *MyRequest) FormParams() map[string]string {
	return map[string]string{
		"params_name": "666",
	}
}

type HeaderGetter

type HeaderGetter interface{ Header() map[string]string }

HeaderGetter returns the headers of the current request

Implement this interface to automatically set headers in the current HTTP request.

Usage Example:

type MyRequest struct{}

func (s *MyRequest) Header() map[string]string {
	return map[string]string{
		"Content-Type": "application/json;charset=UTF-8",
	}
}

type MethodGetter

type MethodGetter interface {
	Method() string
}

MethodGetter returns http method

Implement this interface to set the method for current current HTTP request.

Usage Example:

type MyRequest struct{}

func (s *MyRequest) Method() { return http.MethodGet }

type PathParamsGetter

type PathParamsGetter interface{ PathParams() map[string]string }

PathParamsGetter returns the parameters in the current request path

Implement this interface to automatically set the parameters in the current HTTP request path.

URL Format:

   Raw: /api/path/{params_name}
Cooked: /api/path/666

Usage Example:

type MyRequest struct{}

func (s *MyRequest) PathParams() map[string]string {
	return map[string]string{
		"params_name": "666",
	}
}

type QueryParamsGetter

type QueryParamsGetter interface{ QueryParams() map[string]string }

QueryParamsGetter returns the query parameters in the current request

Implement this interface to automatically set the query parameters in the current HTTP request.

URL Format:

/api/path?params_1=value_1&params_2=value_2

Usage Example:

type MyRequest struct{}

func (s *MyRequest) QueryParams() map[string]string {
	return map[string]string{
		"params_1": "value_1",
		"params_2": "value_2",
	}
}

type QueryStringGetter

type QueryStringGetter interface{ QueryString() string }

QueryStringGetter returns the query parameters string in the current request

Implement this interface to automatically set the query parameters string in the current HTTP request.

URL Format:

/api/path?params_1=value_1&params_2=value_2

Usage Example:

type MyRequest struct{}

func (s *MyRequest) QueryString() string {
	return "params_1=value_1&params_2=value_2"
}

type RequestChecker added in v0.1.3

type RequestChecker interface{ Check() error }

RequestChecker check current request

Implement this interface to automatically check current HTTP request.

Usage Example:

type MyRequest struct{}

func (s *MyRequest) Check() error {
	if s == nil {
		return fmt.Error("invalid request")
	}
	return nil
}

type RequestOption

type RequestOption func(r *resty.Request)

RequestOption request option

type RequestProtocol

type RequestProtocol interface {
	Host() string
	Path() string
}

RequestProtocol custom request protocol

By implementing the appropriate Getter interface for the request protocol, various options in the request can be set automatically.

Support checker && getter:

	- [RequestChecker]                        // check current request.
	- [MethodGetter]                          // sets the http method
	- [BasicAuthGetter]                       // sets the basic authentication header
	- [BearerTokenAuthGetter]                 // sets the auth token header
	- [CookiesGetter]                         // append cookies
	- [HeaderGetter]                          // set multiple header fields and their values
	- [PathParamsGetter]                      // set multiple URL path key-value pair
	- [QueryParamsGetter]                     // set multiple parameter
	- [QueryStringGetter]                     // set the query string
	- [FormParamsGetter]                      // set form parameters and their values
	- [BodyGetter]                            // set the request body
	- [TimeoutGetter]                         // set the request timeout
	- [RetryGetter]                           // set the retry times and conditions when the request failed
	- [RetryWaitGetter]                       // set the default wait time for sleep before retrying
	- [RetryHooksGetter]                      // set retry hooks
	- [AllowResponseBodyUnlimitedReadsGetter] // enable the response body in memory that provides an ability to do unlimited reads.
	- [AllowMethodGetPayloadGetter]           // allows the GET method with payload.
	- [AllowMethodDeletePayloadGetter]        // allows the DELETE method with payload.
	- [DebugGetter]                           // enable debug mode.
	- [TraceGetter]                           // enable trace for current request.
	- [ExpectResponseContentTypeGetter]       // set fallback `Content-Type`.
	- [ForceResponseContentTypeGetter]        // set force response `Content-Type`.

type RetryGetter

type RetryGetter interface {
	Retry() (retryTimes int, retryConds []resty.RetryConditionFunc)
}

RetryGetter returns retry strategy for current request

Implement this interface to automatically set the retry strategy for current HTTP request.

Usage Example:

type MyRequest struct{}

func (s *MyRequest) Retry() (retryTimes int, retryConds []resty.RetryConditionFunc) {
	// retry 3 times when response code is http.StatusTooManyRequests or http.StatusBadRequest
	return 3, []resty.RetryConditionFunc {
		httpx.RetryWithStatusCodes(http.StatusTooManyRequests, http.StatusBadRequest),
	}

	// retry 3 times when returns error
	return 3, nil
}

type RetryHooksGetter

type RetryHooksGetter interface {
	RetryHooks(ctx context.Context) []resty.RetryHookFunc
}

RetryHooksGetter returns retry hooks for current request

Implement this interface to automatically set the retry hooks for current HTTP request.

Usage Example:

type MyRequest struct{}

func (s *MyRequest) RetryHooks(ctx context.Context) []resty.RetryHookFunc {
	return []resty.RetryHookFunc{
		func(r *resty.Response, err error) {
			if err != nil {
				fmt.Printf("retry once, because an error occurred, error:%+v", err)
				return
			}

			if r != nil && r.Result() != nil {
				fmt.Printf("retry once, response:%+v", r.Result())
			}
		},
	}
}

type RetryWaitGetter

type RetryWaitGetter interface{ RetryWait() time.Duration }

RetryWaitGetter returns the wait time before retry sleep for current request

Implement this interface to automatically set the wait time before retry sleep for current HTTP request.

Usage Example:

type MyRequest struct{}

func (s *MyRequest) RetryWait() time.Duration {
	return time.Second
}

type TimeoutGetter

type TimeoutGetter interface{ Timeout() time.Duration }

TimeoutGetter returns timeout for current request

Implement this interface to automatically set the timeout for current HTTP request.

Usage Example:

type MyRequest struct{}

func (s *MyRequest) Timeout() any {
	return 3 * time.Second
}

type TraceGetter added in v0.1.2

type TraceGetter interface{ Trace() }

TraceGetter return nothing

Implement this interface will enables trace for the current request.

Usage Example:

type MyRequest struct{}

func (s *MyRequest) Trace() {}

Directories

Path Synopsis
Package mockhttpx is a generated GoMock package.
Package mockhttpx is a generated GoMock package.

Jump to

Keyboard shortcuts

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