gloria

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 31, 2023 License: MIT Imports: 21 Imported by: 0

README

gloria

Go version Release GoDoc License

Gloria is a minimalist and elegant HTTP client tool designed to embrace the beauty of RESTful style. Gloria draws inspiration from Go resty, Python requests, and JavaScript axios.

English | 简体中文

Origin

The term "Gloria" is derived from the hit song in G.E.M.'s album "Revelation". We hope that this library can provide a wonderful experience just like G.E.M.'s music.

Additionally, Gloria carries the meaning of "glory" in Latin, symbolizing the library's design to offer a glorious and elegant way of using the Go HTTP client. Similar to the RESTful specification, it aims to make network requests more in line with human natural habits.

We pay tribute to all those who strive to build internet applications and hope that Gloria can bring them a more comfortable development and user experience.

Features

  • 🪶 Simple, user-friendly, and versatile API design
  • 👏 Unified RESTful-style response implementation using generics
  • 🚀 Support for injecting multiple request and response interceptors
  • 🎁 Support for registering third-party JSON parsing libraries
  • 📝 Detailed colored logging and error tracing capabilities
  • 💃🏼 Elegant error handling with Unwrap (Rust-style)
  • 🧭 Request invocation time and QPS estimation functionality
  • 🌈 Support for GET, POST, PUT, DELETE, and more
  • 🎋 Thorough Benchmark testing for optimal performance

Usage

Version

Supported versions: Requires the Go T generics feature and a minimum interpreter version of go1.18+.

Installation

Using Gloria is easy. First, use go get to install the latest version of the library.

go get -u github.com/pokeyaro/gloria@latest

Import

import "github.com/pokeyaro/gloria"

Index

Documentation

Through the following examples, you can quickly get started and learn about the gloria library.

Simple GET Request

For a real API, you can use: curl -X GET --location 'http://httpbin.org/get'

Example 1

To demonstrate how to use gloria in a clear way, we will use the NewHTTP() method and explain the steps involved:

Example code: api-httpbin.go   |   Recommended 🌟🌟🌟

// Preparing the response body struct.
type HttpBin struct {
    Args struct {
    } `json:"args"`
    Headers struct {
        Accept                  string `json:"Accept"`
        AcceptEncoding          string `json:"Accept-Encoding"`
        AcceptLanguage          string `json:"Accept-Language"`
        Host                    string `json:"Host"`
        UpgradeInsecureRequests string `json:"Upgrade-Insecure-Requests"`
        UserAgent               string `json:"User-Agent"`
        XAmznTraceId            string `json:"X-Amzn-Trace-Id"`
    } `json:"headers"`
    Origin string `json:"origin"`
    Url    string `json:"url"`
}

// Building a request using the NewHTTP method.
client := gloria.NewHTTP[HttpBin]()

// Setting the request type.
client.SetMethod(gloria.MethodGet)

// Setting the request's request route resource (URL segments: proto, host, baseURI, endpoint).
client.SetURL(gloria.ProtocolHttp, "httpbin.org", "", "/get")

// Sending the request.
client.Send()

// Handling errors.
client.Unwrap()

// Printing request metadata.
client.Echo()

/* Output:
[API Call Insights]
  Mode       : HTTP Response
  Error      : <nil>
  Method     : GET
  URL        : http://httpbin.org/get
  Status     : 200 OK
  Benchmark  : 1	1534950042 ns/op
  Proto      : HTTP/1.1
  QPS        : 0.651487
  Duration   : 1.534950042s
  Received At: Saturday, 20-May-23 23:28:11 CST
  Body       : -
*/
Example 2

Providing users with a more concise API method and supporting chain loading, so you can write it like this:

Example code: api-httpbin.go   |   Recommended 🌟🌟🌟🌟🌟

type HttpBin struct {
    // omitted...
}

// Request
client, _ := gloria.NewHTTP[HttpBin]().SetRequest(gloria.MethodGet, "http://httpbin.org/get").Send().Unwrap()

// Retrieve
fmt.Println(client.Data().Url)

/* Output:
http://httpbin.org/get
*/

More Advanced Request Configuration

For a real API, you can use: curl -X GET --location 'https://api.thecatapi.com/v1/images/search?size=med&mime_types=png%2Cgif&format=json&order=RANDOM&limit=20' --header 'Content-Type: application/json'

Example 1

Let's experience the richer configuration options provided by New() and Optional() methods:

Example code: api-cat.go   |   Recommended 🌟🌟🌟🌟

// Preparing the response body struct.
type ImageSearch struct {
    Id     string `json:"id"`
    Url    string `json:"url"`
    Width  int    `json:"width"`
    Height int    `json:"height"`
}

// Build a more comprehensive request.
func GetCatAPI() {
    // This API returns a slice of struct.
    r := gloria.New[[]ImageSearch]()

    r.Optional(
        // Whether to enable debug mode.
        gloria.WithIsDebug[[]ImageSearch](false),
        // Whether to enable logging.
        gloria.WithUseLogger[[]ImageSearch](true),
        // Setting additional parameters using the lambda syntax.
        gloria.Lambda[[]ImageSearch](func(c *gloria.Client[[]ImageSearch]) {
            c.Config.SkipTLS = true
            c.Config.Timeout = gloria.TimeoutMedium
            c.Config.FilterSlash = true // Filter trailing slashes in URLs (use with caution).
            c.Config.IsRestMode = false // If it's a non-standard RESTful response interface, use native HTTP mode by selecting false.
        }),
    ).
        // Set the request method.
        SetMethod(gloria.MethodGet).
        // Set the request path. This method requires specifying the path in segments.
        SetURL(gloria.ProtocolHttps, "api.thecatapi.com", "/v1", "/images/search").
        // Set multiple request parameters.
        SetQueryParams(gloria.H{
            "size":       "med",
            "mime_types": []string{"png", "gif"},
            "format":     "json",
            "order":      "RANDOM",
            "limit":      20,
        }).
        // Set multiple request headers.
        SetHeaders(gloria.H{
            "x-api-key": "live_example-api-key",
            "Content-Type": "application/json",
        }).
        // Sending the request.
        Send().
        Unwrap()

    fmt.Println(r.Data()[0].Url)	
}
Example 2

Use Default() to load default configurations. In fact, you don't need to worry about the difference between Default() and New(), or what default parameters it adds internally. If you are curious and want to know more, you can use the go doc gloria.Default command to check.

Example code: api-cat.go   |   Recommended 🌟🌟🌟🌟🌟

type ImageSearch struct {
    // omitted...
}

// Build a more sophisticated request.
func GetCatAPI() {
    // Note that the Default() method operates in REST mode. To switch to another mode, use ToggleMode().
    r := gloria.Default[[]ImageSearch]().ToggleMode()

    r.
        SetRequest(gloria.MethodGet, "https://api.thecatapi.com/v1/images/search").
        SetQueryParams(gloria.H{
            "size":       "med",
            "mime_types": []string{"png", "gif"},
            "format":     "json",
            "order":      "RANDOM",
            "limit":      20,
        }).
        SetHeader("x-api-key", "live_example-api-key").
        SetContentType(gloria.JsonContentType).
        Send().Unwrap()

    fmt.Println(r.Result.Data[0].Url)
}

Common CRUD Request Operations

Below demonstrates the CRUD operations of the API, including Create [POST], Read [GET], Update [PUT], and Delete [DELETE].

Example of [GET] Request

Example code: api-cat.go   |   Recommended 🌟🌟🌟🌟🌟

type FavouritesList struct {
    Id        int       `json:"id"`
    UserId    string    `json:"user_id"`
    ImageId   string    `json:"image_id"`
    SubId     string    `json:"sub_id"`
    CreatedAt time.Time `json:"created_at"`
    Image     struct {
        Id  string `json:"id,omitempty"`
        Url string `json:"url,omitempty"`
    } `json:"image"`
}

// GET
func main() {
    r := gloria.NewHTTP[[]FavouritesList]()

    r.SetRequest(gloria.MethodGet, "https://api.thecatapi.com/v1/favourites").SetHeaders(gloria.H{
        "x-api-key":    "your-api-key",
        "Content-Type": "application/json",
    }).Send().Unwrap()

    for _, v := range r.Data() {
        fmt.Println(v)
    }
}
Example of [POST] Request

Example code: api-cat.go   |   Recommended 🌟🌟🌟🌟🌟

type FavouriteImgResp struct {
    Message string `json:"message"`
    Id      int    `json:"id"`
}

type FavouriteImgBody struct {
    ImageId string `json:"image_id"`
    SubId   string `json:"sub_id"`
}

// POST
func main() {
    data := FavouriteImgBody{
        ImageId: "12345",
        SubId:   "my-key-12345",
    }

    r := gloria.NewHTTP[FavouriteImgResp]()

    r.SetRequest(gloria.MethodPost, "https://api.thecatapi.com/v1/favourites").SetHeaders(gloria.H{
        "x-api-key":    "your-api-key",
        "Content-Type": "application/json",
    }).SetPayload(&data).Send().Unwrap()

    fmt.Println("post_id:", r.Data().Id)
}
Example of [PUT] Request

No example available. Please refer to the POST method for reference.

Example of [DELETE] Request

Example code: api-cat.go   |   Recommended 🌟🌟🌟🌟🌟

type Result struct {
    Message string `json:"message"`
}

// DELETE
func main() {
    r := gloria.NewHTTP[Result]()

    r.SetRequest(gloria.MethodDelete, "https://api.thecatapi.com/v1/favourites/:id", "232338734").SetHeaders(gloria.H{
        "x-api-key":    "your-api-key",
        "Content-Type": "application/json",
    }).Send().Unwrap()

    fmt.Println("message:", r.Data().Message)
}

Two Response Modes

There are two different response modes: HTTP mode and REST mode. Let's explain the differences between them!

In the HTTP mode, the response data can be of any format. As shown in the previous example, there are no specific conventions or standards to follow. It provides more flexibility.

In the REST mode, if your response follows the format shown below:

{
  "code": 0,
  "msg": "success",
  "data": Object,
}

Understood! In the REST mode, we directly parse the data in the data field, making your data request and response more straightforward and direct.

Below is a table summarizing the API usage:

Response Format Method Selection Scenario Description
HTTP mode Method 1: New().ToggleMode()
Method 2: Default().ToggleMode()
Method 3: NewHTTP() // Essence: Same as Method 1.
If your response format is non-standard for RESTful response interface, please use the more general HTTP mode.
REST mode Method 1: New()
Method 2: Default()
Method 3: NewREST() // Essence: Same as Method 1.
When your response format follows the standard RESTful response interface, like: {"code": 0, "msg": "success", "data": null}

REST Syntactic Sugar

Advantage: The syntax is simpler, and all configurations are parsed and sent within this function. Therefore, it can be seen as an advantage as well as a disadvantage.

Disadvantage: As mentioned above, it does not currently support more advanced syntax, such as chaining other settings directly within these function calls. Hence, it limits the flexibility to inject other configurations in a chain-like manner.

When using the REST mode to construct and handle requests, two additional convenient syntax sugars are provided.

Python Requests-style

Example code: requests-style.go   |   Recommended 🌟🌟🌟🌟🌟

func Request[T any](path string, params H, data any, headers ...H) ExecMethod[T]

func GET[T any](path string, params H, headers ...H) *Client[T]

func POST[T any](path string, params H, data any, headers ...H) *Client[T]

func PUT[T any](path string, params H, data any, headers ...H) *Client[T]

func DELETE[T any](path string, params H, data any, headers ...H) *Client[T]

func PATCH[T any](path string, params H, data any, headers ...H) *Client[T]

func HEAD[T any](path string, params H, headers ...H) *Client[T]

func OPTIONS[T any](path string, headers ...H) *Client[T]
JavaScript Axios-style

Example code: try-catch-style.go   |   Recommended 🌟🌟🌟🌟

gloria.GET[T]().
    Then(func(data T) {}).
    Catch(func(e *gloria.Exception) {}).
    Finally(func(c *gloria.Client[Result]) {}, bool)

More API Function Signatures

func New[T any]() *Client[T]
func Default[T any]() *Client[T]

func NewREST[T any]() *Client[T]
func NewHTTP[T any]() *Client[T]
func (c *Client[T]) Optional(fns ...ClientFunc[T]) *Client[T]

func Lambda[T any](f func(*Client[T])) ClientFunc[T]

func WithTimeout[T any](timeout time.Duration) ClientFunc[T]
func WithSkipTLS[T any](skipTLS bool) ClientFunc[T]
func WithIsDebug[T any](isDebug bool) ClientFunc[T]
func WithUseLogger[T any](enabled bool) ClientFunc[T]

func (c *Client[T]) ToggleMode() *Client[T]                     // Toggle to the other mode.
func (c *Client[T]) FilterUrlSlash() *Client[T]                 // Trailing slashes in URLs will be automatically filtered out.
func (c *Client[T]) DefineOkCode(code int) *Client[T]           // Set a custom success value to be used as a basis for automatically determining business failures.
func (c *Client[T]) RegisterJsonLib(lib JSONLibrary) *Client[T] // Register JSON parsing library, and you can choose popular third-party libraries independently and dynamically.
func (c *Client[T]) SetMethod(method string) *Client[T]

func (c *Client[T]) SetSchema(scheme string) *Client[T]
func (c *Client[T]) SetHost(host string) *Client[T]
func (c *Client[T]) SetBaseURI(baseUri string) *Client[T]
func (c *Client[T]) SetEndpoint(endpoint string) *Client[T]

func (c *Client[T]) SetURL(scheme, host, baseUri, endpoint string) *Client[T]

func (c *Client[T]) SetRequest(method, path string, pathParams ...string) *Client[T]

func (c *Client[T]) SetQueryParam(key, value string) *Client[T]
func (c *Client[T]) SetQueryParams(params H) *Client[T]

func (c *Client[T]) SetHeader(key, value string) *Client[T]
func (c *Client[T]) SetHeaders(headers H) *Client[T]

func (c *Client[T]) SetCookie(cookie *http.Cookie) *Client[T]
func (c *Client[T]) SetCookies(cookies []*http.Cookie) *Client[T]

func (c *Client[T]) SetBasicAuth(username, password string) *Client[T]
func (c *Client[T]) SetBearerAuth(token string) *Client[T]

func (c *Client[T]) SetAccept(accept string) *Client[T]
func (c *Client[T]) SetContentType(ct string) *Client[T]
func (c *Client[T]) SetLanguage(lang string) *Client[T]
func (c *Client[T]) SetUserAgent(ua string) *Client[T]
func (c *Client[T]) UsePreHooks(funcs ...beforeRequest[T])
func (c *Client[T]) UsePostHooks(funcs ...afterResponse[T])
func (c *Client[T]) Send() *Client[T]

func (c *Client[T]) Unwrap() (*Client[T], string)

func GET[T any](path string, params H, headers ...H) *Client[T]
func POST[T any](path string, params H, data any, headers ...H) *Client[T]
func PUT[T any](path string, params H, data any, headers ...H) *Client[T]
func DELETE[T any](path string, params H, data any, headers ...H) *Client[T]
func PATCH[T any](path string, params H, data any, headers ...H) *Client[T]
func HEAD[T any](path string, params H, headers ...H) *Client[T]
func OPTIONS[T any](path string, headers ...H) *Client[T]

func Request[T any](path string, params H, data any, headers ...H) ExecMethod[T]

func (c *Client[T]) Then(cb CallbackOk[T]) *Client[T]
func (c *Client[T]) Catch(cb CallbackErr) *Client[T]
func (c *Client[T]) Finally(cb CallbackExtra[T], printLog ...bool)

func (c *Client[T]) Data() T
func (c *Client[T]) Query(q string) string
func (c *Client[T]) QueryParams() SMap

func (c *Client[T]) Header(key string) string
func (c *Client[T]) Headers() http.Header

func (c *Client[T]) Cookie(name string) (*http.Cookie, error)
func (c *Client[T]) Cookies() []*http.Cookie
func (c *Client[T]) Echo()

func (c *Client[T]) EchoURL() (string, string)
func (c *Client[T]) EchoCode() (int, int)
func (c *Client[T]) EchoMessage() (string, string)
func (c *Client[T]) EchoProto() string
func (c *Client[T]) EchoMode() string
func (c *Client[T]) EchoQPS() float64
func (c *Client[T]) EchoBenchmark() (int, int64)
func (c *Client[T]) EchoTime() (time.Duration, time.Time)
func (l level) ANSIColorCode() string

func (c *Client[T]) ChalkObj(level level, obj any) *Client[T]
func (c *Client[T]) ChalkStr(level level, s string) *Client[T]
func (c *Client[T]) ChalkInt(level level, n int) *Client[T]
func (c *Client[T]) ChalkPrintf(level level, format string, args ...any) *Client[T]

Injecting Interceptors for HTTP

Injection timing

Please note the timing of loading request and response interceptors (middlewares):

client := New[any]()

client.Setxxx().Setxxx()

// Add multiple request hooks
client.UsePreHooks(func(c *Client[[]ImageSearch]) error {
    fmt.Println("1. I am a request hook 🪝🪝🪝")
    return nil
}, func(c *Client[[]ImageSearch]) error {
    fmt.Println("2. I am a request hook 🐒🐒🐒")
    return nil
})

// Add multiple response hooks
client.UsePostHooks(func(c *Client[[]ImageSearch]) error {
    fmt.Println("3. I am a response hook 🪝🪝🪝")
    return nil
}, func(c *Client[[]ImageSearch]) error {
    fmt.Println("4. I am a response hook 🍌🍌🍌")
    return nil
})

// Note that the hooks should be added before calling Send!
client.Send().Unwrap()
Execution order

First, the request hooks functions will be executed in the order they were added. Then the request will be sent. Finally, the response hooks functions will be executed in the order they were added.

1. I am a request hook 🪝🪝🪝
2. I am a request hook 🐒🐒🐒
Sending request...
3. I am a response hook 🪝🪝🪝
4. I am a response hook 🍌🍌🍌

Register a high-performance JSON parsing library

Sonic library

For example, inject bytedance/sonic an blazingly fast JSON serializing & deserializing library.

import "github.com/bytedance/sonic"

// bytedance/sonic interface implementation
type SonicLibrary struct{}

func (l SonicLibrary) Marshal(v interface{}) ([]byte, error) {
    return sonic.Marshal(v)
}

func (l SonicLibrary) Unmarshal(data []byte, v interface{}) error {
    return sonic.Unmarshal(data, v)
}

// how to use?
client := New[any]()

client.RegisterJsonLib(SonicLibrary{})

// continue...
Other library

Of course, you can also use jsoniter, easyjson, go-json (with the Default() function), std (with the native New() function), or any other library you prefer.

Some Coding Suggestions

Type Aliases

It is recommended to use predefined type aliases to maintain consistent code style.

type H = map[string]any

type SMap = map[string]string

// "http://example.org/?uid=47200957&username=Mystic&is_output=true&mime_types=png,gif,ico"
// When setting request parameters, it is advisable to use the actual data types instead of relying solely on strings.

/* Good example */
c.SetQueryParams(gloria.H{
    "uid": 47200957,
    "username": "Mystic",
    "is_output": true,
    "mime_types": ["png", "gif", "ico"],
})

/* Bad example */
c.SetQueryParams(map[string]interface{}{
    "uid": "47200957",
    "username": "Mystic",
    "is_output": "true",
    "mime_types": "png,gif,ico",
})
Constants

Predefined constants are preferred over hardcoding numbers or strings directly.

/* Good example */
// Use predefined constants from the gloria package, such as:
c.DefineOkCode(gloria.OkCode)

// Use predefined constants from the http package, such as:
c.DefineOkCode(http.StatusOK)

/* Bad example */
c.DefineOkCode(20000)

Contribution

I warmly welcome your contribution! If you come across any areas for improvement or any issues that you would like to fix, please don't hesitate to send a pull request. I appreciate pull requests that include test cases for bug fixes or enhancements. I have put in my best effort to ensure decent code coverage, so feel free to write tests.

By the way, I am curious to hear your thoughts on Gloria. Please feel free to open an issue or send me an email. Your feedback means a great deal to me.

Creator

Pokeya Boa (pokeya.mystic@gmail.com)

License

Gloria released under MIT license, refer LICENSE file.

Documentation

Index

Examples

Constants

View Source
const (
	// MethodGet HTTP method
	MethodGet = "GET"

	// MethodPost HTTP method
	MethodPost = "POST"

	// MethodPut HTTP method
	MethodPut = "PUT"

	// MethodDelete HTTP method
	MethodDelete = "DELETE"

	// MethodPatch HTTP method
	MethodPatch = "PATCH"

	// MethodHead HTTP method
	MethodHead = "HEAD"

	// MethodOptions HTTP method
	MethodOptions = "OPTIONS"
)
View Source
const (
	// ProtocolHttp HTTP protocol
	ProtocolHttp = "http"

	// ProtocolHttps HTTPS protocol
	ProtocolHttps = "https"
)
View Source
const (
	// RootURL an alias for signSlash
	RootURL = signSlash

	// Placeholder an alias for signHorizontal
	Placeholder = signHorizontal
)
View Source
const (
	// OkCode Predefined default success response codes
	OkCode = 0

	// FailCode Predefine default failure response codes
	FailCode = 50000
)
View Source
const (
	// TimeoutShort Short timeout duration (10 seconds)
	TimeoutShort = 10 * time.Second

	// TimeoutMedium Medium timeout duration (30 seconds)
	TimeoutMedium = 30 * time.Second

	// TimeoutLong Long timeout duration (60 seconds)
	TimeoutLong = 60 * time.Second
)
View Source
const (
	// AuthTypeBasic Basic authentication type
	AuthTypeBasic = "Basic"

	// AuthTypeBearer Bearer authentication type
	AuthTypeBearer = "Bearer"
)
View Source
const (
	// LocaleEn English locale
	LocaleEn = "en-US,en;q=0.9"

	// LocaleZh Chinese locale
	LocaleZh = "zh-CN,zh;q=0.9"
)
View Source
const (
	// PlainTextType Plain text content type
	PlainTextType = "text/plain; charset=utf-8"

	// JsonContentType JSON content type
	JsonContentType = "application/json"

	// FormContentType Form data content type
	FormContentType = "application/x-www-form-urlencoded"
)
View Source
const (
	// LogLevelSuccess represents logs at the SUCCESS level
	LogLevelSuccess level = "SUCCESS"

	// LogLevelFail represents logs at the FAIL level
	LogLevelFail level = "FAIL"

	// LogLevelPanic represents logs at the PANIC level
	LogLevelPanic level = "PANIC"

	// LogLevelInfo represents logs at the INFO level
	LogLevelInfo level = "INFO"

	// LogLevelWarn represents logs at the WARN level
	LogLevelWarn level = "WARN"

	// LogLevelDebug represents logs at the DEBUG level
	LogLevelDebug level = "DEBUG"
)

Log levels

Variables

View Source
var (
	HeaderAcceptKey          = http.CanonicalHeaderKey("Accept")
	HeaderLocationKey        = http.CanonicalHeaderKey("Location")
	HeaderUserAgentKey       = http.CanonicalHeaderKey("User-Agent")
	HeaderContentTypeKey     = http.CanonicalHeaderKey("Content-Type")
	HeaderContentLengthKey   = http.CanonicalHeaderKey("Content-Length")
	HeaderContentLanguageKey = http.CanonicalHeaderKey("Content-Language")
	HeaderContentEncodingKey = http.CanonicalHeaderKey("Content-Encoding")
	HeaderAuthorizationKey   = http.CanonicalHeaderKey("Authorization")
)
View Source
var (
	// Title is the name of the project.
	Title string = "Gloria"

	// Version is the version number of the application.
	Version string = "1.0.0"

	// BuildTime is the build time of the application.
	// Better practice: go build -ldflags "-X main.BuildTime=$(date '+%Y-%m-%d %H:%M:%S')" main.go
	BuildTime string = ""

	// GitHash is the commit hash of the application's Git repository.
	GitHash string = ""
)
View Source
var (
	// QueryMethods Method list in a String Slice
	QueryMethods = []string{
		MethodGet,
		MethodPost,
		MethodPut,
		MethodDelete,
		MethodPatch,
		MethodHead,
		MethodOptions,
	}
)

Functions

func DecoratorTimer

func DecoratorTimer(fn func() error)

DecoratorTimer a decorator for timing functions to test api performance.

Types

type CallbackErr

type CallbackErr func(e *Exception)

type CallbackExtra

type CallbackExtra[T any] func(c *Client[T])

type CallbackOk

type CallbackOk[T any] func(data T)

type Client

type Client[T any] struct {
	// context
	Context *Context

	// request metadata
	Meta *Meta

	// request settings
	Config *Config

	// intercepted error
	Exception *Exception

	// expandable body
	Result *RESTFulResp[T]
	// contains filtered or unexported fields
}

func DELETE

func DELETE[T any](path string, params H, data any, headers ...H) *Client[T]

DELETE is a shorthand function for creating a DELETE request with the specified path, query parameters, request body data, and headers. It returns a new client instance configured for a DELETE request.

func Default

func Default[T any]() *Client[T]

Default function returns a basic default template.

Preset parameters:

  1. Debug: false
  2. Logger: true
  3. OkCode: 0
  4. TLS: skip
  5. Timeout: 30s
  6. RestMode: true

Inject default middleware:

  1. set Accept: application/json
  2. set Content-Type: application/json
  3. set Content-Language: en-US,en;q=0.9
  4. set User-Agent: - actual environment

func GET

func GET[T any](path string, params H, headers ...H) *Client[T]

GET is a shorthand function for creating a GET request with the specified path, query parameters, and headers. It returns a new client instance configured for a GET request.

func HEAD[T any](path string, params H, headers ...H) *Client[T]

HEAD is a shorthand function for creating a HEAD request with the specified path, query parameters, request body data, and headers. It returns a new client instance configured for a HEAD request.

func New

func New[T any]() *Client[T]

New function returns an empty template initialization (for rest mode).

func NewClient deprecated

func NewClient() *Client[any]

Deprecated: NewClient function creates an empty template similar to the New function. However, it is not recommended as it no longer has generic type features.

func NewHTTP

func NewHTTP[T any]() *Client[T]

NewHTTP function returns an empty template initialization (for http mode).

Example (Method1)
// Create an HTTP client with HttpBin response struct
client := NewHTTP[HttpBin]()

client.SetMethod(MethodGet)
client.SetURL(ProtocolHttp, "httpbin.org", "", "/get")
client.Send()
client.Unwrap()

client.Echo()
Example (Method2)
// One line response
client, _ := NewHTTP[HttpBin]().SetRequest(MethodGet, "http://httpbin.org/get").Send().Unwrap()

fmt.Println(client.Data().Url)
Output:
http://httpbin.org/get

func NewREST

func NewREST[T any]() *Client[T]

NewREST function returns an empty template initialization (for rest mode).

func OPTIONS

func OPTIONS[T any](path string, headers ...H) *Client[T]

OPTIONS is a shorthand function for creating an OPTIONS request with the specified path and headers. It returns a new client instance configured for an OPTIONS request.

func PATCH

func PATCH[T any](path string, params H, data any, headers ...H) *Client[T]

PATCH is a shorthand function for creating a PATCH request with the specified path, query parameters, request body data, and headers. It returns a new client instance configured for a PATCH request.

func POST

func POST[T any](path string, params H, data any, headers ...H) *Client[T]

POST is a shorthand function for creating a POST request with the specified path, query parameters, request body data, and headers. It returns a new client instance configured for a POST request.

func PUT

func PUT[T any](path string, params H, data any, headers ...H) *Client[T]

PUT is a shorthand function for creating a PUT request with the specified path, query parameters, request body data, and headers. It returns a new client instance configured for a PUT request.

func (*Client[T]) Catch

func (c *Client[T]) Catch(cb CallbackErr) *Client[T]

Catch sets a callback function to be executed when an exception occurs during the HTTP request. The provided callback function cb is invoked only if an exception exists in the client instance. The cb function is called with the exception object as its argument. After executing the callback function, the client instance is returned.

func (*Client[T]) ChalkInt

func (c *Client[T]) ChalkInt(level level, n int) *Client[T]

ChalkInt writes a log entry with the specified level and integer value. The 'level' parameter represents the log level. The 'n' parameter is the integer to be logged. It returns the updated Client instance.

func (*Client[T]) ChalkObj

func (c *Client[T]) ChalkObj(level level, obj any) *Client[T]

ChalkObj writes a log entry with the specified level and object value. It uses reflection to extract the value from the object parameter. The 'level' parameter represents the log level. The 'obj' parameter is the object to be logged. It returns the updated Client instance.

func (*Client[T]) ChalkPrintf

func (c *Client[T]) ChalkPrintf(level level, format string, args ...any) *Client[T]

ChalkPrintf writes a formatted log entry with the specified level and arguments. The 'level' parameter represents the log level. The 'format' parameter is the format string for the log message. The 'args' parameter contains the arguments to be formatted. It returns the updated Client instance.

func (*Client[T]) ChalkStr

func (c *Client[T]) ChalkStr(level level, s string) *Client[T]

ChalkStr writes a log entry with the specified level and string value. The 'level' parameter represents the log level. The 's' parameter is the string to be logged. It returns the updated Client instance.

func (*Client[T]) Cookie added in v0.1.6

func (c *Client[T]) Cookie(name string) (*http.Cookie, error)

Cookie returns the cookie with the specified name from the client's request context. If the cookie is found, it returns the cookie object. If the cookie is not found, it returns an error.

func (*Client[T]) Cookies added in v0.1.6

func (c *Client[T]) Cookies() []*http.Cookie

Cookies returns the cookies as a []*http.Cookie from the client's request context.

func (*Client[T]) Data

func (c *Client[T]) Data() T

func (*Client[T]) DefineOkCode

func (c *Client[T]) DefineOkCode(code int) *Client[T]

func (*Client[T]) Echo

func (c *Client[T]) Echo()

func (*Client[T]) EchoBenchmark

func (c *Client[T]) EchoBenchmark() (int, int64)

func (*Client[T]) EchoCode

func (c *Client[T]) EchoCode() (int, int)

func (*Client[T]) EchoMessage

func (c *Client[T]) EchoMessage() (string, string)

func (*Client[T]) EchoMode

func (c *Client[T]) EchoMode() string

func (*Client[T]) EchoProto

func (c *Client[T]) EchoProto() string

func (*Client[T]) EchoQPS

func (c *Client[T]) EchoQPS() float64

func (*Client[T]) EchoTime

func (c *Client[T]) EchoTime() (time.Duration, time.Time)

func (*Client[T]) EchoURL

func (c *Client[T]) EchoURL() (string, string)

func (*Client[T]) FilterUrlSlash added in v0.1.4

func (c *Client[T]) FilterUrlSlash() *Client[T]

Note: The FilterUrlSlash method needs to be called before the SetURL or SetRequest method.

func (*Client[T]) Finally

func (c *Client[T]) Finally(cb CallbackExtra[T], printLog ...bool)

Finally function is a flexible custom callback function with checkpoint functionality.

func (*Client[T]) Header added in v0.1.6

func (c *Client[T]) Header(key string) string

Header returns the value of the specified header key from the client's request context.

func (*Client[T]) Headers added in v0.1.6

func (c *Client[T]) Headers() http.Header

Headers returns the headers as a http.Header from the client's request context.

func (*Client[T]) Optional

func (c *Client[T]) Optional(fns ...ClientFunc[T]) *Client[T]

Optional is a method that allows applying optional configurations to the client instance. It accepts a variadic parameter fns, which represents a list of client functions to be applied. Each function takes the client instance as a parameter and applies specific configurations or modifications to it. The method iterates over the list of functions and calls each function with the client instance as an argument. After applying all the functions, it returns the modified client instance.

func (*Client[T]) Query added in v0.1.6

func (c *Client[T]) Query(q string) string

Query returns the value of the specified query parameter from the client instance.

func (*Client[T]) QueryParams added in v0.1.6

func (c *Client[T]) QueryParams() SMap

QueryParams returns the query parameters as a SMap from the client instance.

func (*Client[T]) RegisterJsonLib added in v0.1.5

func (c *Client[T]) RegisterJsonLib(lib JSONLibrary) *Client[T]

Note: Please implement the JSONLibrary interface definition yourself.

func (*Client[T]) Send

func (c *Client[T]) Send() *Client[T]

func (*Client[T]) SetAccept

func (c *Client[T]) SetAccept(accept string) *Client[T]

SetAccept sets the value of the "Accept" header for the request. It takes an `accept` parameter, which is a string representing the value of the "Accept" header. This method allows specifying the desired media type for the response. It returns a pointer to the `Client` instance to allow for method chaining.

Example usage:

client.SetAccept("application/json")

func (*Client[T]) SetBaseURI

func (c *Client[T]) SetBaseURI(baseUri string) *Client[T]

SetBaseURI sets the base URI for the client instance.

This method is called by the SetURL method to set the complete URL for the client instance.

See SetURL.

func (*Client[T]) SetBasicAuth

func (c *Client[T]) SetBasicAuth(username, password string) *Client[T]

SetBasicAuth sets the Basic Authentication credentials for the request. It takes a `username` and `password` as parameters and sets them as the Basic Authentication credentials in the `Client` instance. The `username` parameter represents the username for the Basic Authentication. The `password` parameter represents the password for the Basic Authentication. This method replaces any existing authorization credentials in the `Client` instance with the new Basic Authentication credentials. It returns a pointer to the `Client` instance to allow for method chaining.

Example usage:

client.SetBasicAuth("username", "password")

func (*Client[T]) SetBearerAuth

func (c *Client[T]) SetBearerAuth(token string) *Client[T]

SetBearerAuth sets the Bearer Token for the request. It takes a `token` as a parameter and sets it as the Bearer Token in the `Client` instance. The `token` parameter represents the Bearer Token for the authentication. This method replaces any existing authorization credentials in the `Client` instance with the new Bearer Token. It returns a pointer to the `Client` instance to allow for method chaining.

Example usage:

client.SetBearerAuth("your-token")

func (*Client[T]) SetContentType

func (c *Client[T]) SetContentType(ct string) *Client[T]

SetContentType sets the value of the "Content-Type" header for the request. It takes a `ct` parameter, which is a string representing the value of the "Content-Type" header. This method allows specifying the media type of the request payload. It returns a pointer to the `Client` instance to allow for method chaining.

Example usage:

client.SetContentType("application/json")

func (*Client[T]) SetCookie

func (c *Client[T]) SetCookie(cookie *http.Cookie) *Client[T]

SetCookie adds a cookie to the request headers. It takes a `cookie` parameter, which is a pointer to an `http.Cookie` representing the cookie to be added. This method allows adding a cookie to the request headers. It returns a pointer to the `Client` instance to allow for method chaining.

Example usage:

cookie := &http.Cookie{
	Name:  "session",
	Value: "1234567890",
}
client.SetCookie(cookie)

func (*Client[T]) SetCookies

func (c *Client[T]) SetCookies(cookies []*http.Cookie) *Client[T]

SetCookies sets the cookies for the request headers. It takes a `cookies` parameter, which is a slice of pointers to `http.Cookie` representing the cookies to be set. This method allows setting multiple cookies for the request headers. It returns a pointer to the `Client` instance to allow for method chaining.

Example usage:

cookie1 := &http.Cookie{
	Name:  "session",
	Value: "1234567890",
}
cookie2 := &http.Cookie{
	Name:  "user",
	Value: "john.doe",
}
cookies := []*http.Cookie{cookie1, cookie2}
client.SetCookies(cookies)

func (*Client[T]) SetEndpoint

func (c *Client[T]) SetEndpoint(endpoint string) *Client[T]

SetEndpoint sets the API endpoint for the client instance to the specified endpoint.

This method is called by the SetURL method to set the complete URL for the client instance.

See SetURL.

func (*Client[T]) SetHeader

func (c *Client[T]) SetHeader(key, value string) *Client[T]

SetHeader sets a custom header for the request. It takes a `key` and `value` as parameters and adds the header to the `Client` instance. The `key` parameter represents the header key, and the `value` parameter represents the header value. This method allows adding custom headers to the request. It returns a pointer to the `Client` instance to allow for method chaining.

Example usage:

client.SetHeader("Content-Type", "application/json")

func (*Client[T]) SetHeaders

func (c *Client[T]) SetHeaders(headers H) *Client[T]

SetHeaders sets multiple custom headers for the request. It takes a `headers` parameter, which is a map[string]string representing the headers to be set. Each key-value pair in the `headers` map corresponds to a header key and value, respectively. This method allows setting multiple custom headers at once. It returns a pointer to the `Client` instance to allow for method chaining.

Example usage:

headers := map[string]any{
	"Content-Type":  "application/json",
	"Authorization": "Bearer <token>",
}
client.SetHeaders(headers)

func (*Client[T]) SetHost

func (c *Client[T]) SetHost(host string) *Client[T]

SetHost sets the host URL for the client instance.

This method is called by the SetURL method to set the complete URL for the client instance.

See SetURL.

func (*Client[T]) SetJsonPayload

func (c *Client[T]) SetJsonPayload(data H) *Client[T]

SetJsonPayload sets the JSON payload for the request. It takes a `data` parameter, which is a map[string]any representing the JSON data to be sent in the request body. This method is used for making JSON-encoded POST or PUT requests. It returns a pointer to the `Client` instance to allow for method chaining.

Example usage:

payload := map[string]interface{}{
	"name":  "John Doe",
	"email": "john.doe@example.com",
}
client.SetJsonPayload(payload)

func (*Client[T]) SetLanguage

func (c *Client[T]) SetLanguage(lang string) *Client[T]

SetLanguage sets the value of the "Accept-Language" header for the request. It takes a `lang` parameter, which is a string representing the value of the "Accept-Language" header. This method allows specifying the preferred language for the response. It returns a pointer to the `Client` instance to allow for method chaining.

Example usage:

client.SetLanguage("en-US")

func (*Client[T]) SetMethod

func (c *Client[T]) SetMethod(method string) *Client[T]

SetMethod sets the HTTP method for the client instance to the specified method. This method must be one of the supported methods: GET, POST, PUT, PATCH, DELETE, HEAD, or OPTIONS.

If an unsupported method is provided, this method will panic with an error message indicating the supported methods.

Example usage:

client.SetMethod("GET")

func (*Client[T]) SetPayload

func (c *Client[T]) SetPayload(data any) *Client[T]

SetPayload sets the payload for the request. It takes a `data` parameter of any type representing the data to be sent in the request body. This method is used for making generic POST or PUT requests. It returns a pointer to the `Client` instance to allow for method chaining.

Example usage:

payload := "Hello, World!"
client.SetPayload(payload)

func (*Client[T]) SetQueryParam

func (c *Client[T]) SetQueryParam(key, value string) *Client[T]

SetQueryParam sets a query parameter for the request. It takes a key and value as parameters and adds them to the params map of the Client instance. It returns a pointer to the Client instance, allowing for method chaining.

Example usage:

client.SetQueryParam("key", "value")

func (*Client[T]) SetQueryParams

func (c *Client[T]) SetQueryParams(params H) *Client[T]

SetQueryParams sets multiple query parameters for the request. It takes a `params` map as a parameter and converts it to the `SMap` type, which is used to store query parameters in the `Client` instance. The `params` map contains key-value pairs where the keys represent the query parameter names and the values represent the query parameter values. This method replaces any existing query parameters in the `params` map of the `Client` instance with the new ones. It returns a pointer to the `Client` instance to allow for method chaining.

Example usage:

params := H{"key1": "value1", "key2": "value2"}
client.SetQueryParams(params)

func (*Client[T]) SetRequest

func (c *Client[T]) SetRequest(method, path string, pathParams ...string) *Client[T]

SetRequest sets the request method and path for the client. It also supports dynamic routing by replacing path parameters with actual values. The method parameter specifies the HTTP method (e.g., "GET", "POST", "PUT", etc.). The path parameter specifies the request path with optional path parameters. The pathParams parameter is an optional variadic parameter that contains the values to replace the path parameters in the request path. It returns the modified client instance.

Dynamic Routing: The SetRequest function supports dynamic routing by allowing you to replace path parameters in the request path with actual values. If there is only one path parameter, you can use the placeholder ":id" in the path. If there are two path parameters, the first one should be replaced with ":id" and the second one with ":sid".

Example:

client := NewClient()
client.SetRequest("GET", "/users/:id", "123")
client.SetRequest("POST", "/users/:id/:sid", "123", "456")

In the above example, the first SetRequest call sets the request method to "GET" and the request path to "/users/123". The second SetRequest call sets the request method to "POST" and the request path to "/users/123/456".

Note: The SetRequest function currently supports a maximum of two dynamic routing parameters. If more than two path parameters are provided, a panic will occur.

func (*Client[T]) SetSchema

func (c *Client[T]) SetSchema(scheme string) *Client[T]

SetSchema sets the protocol scheme for the client instance.

This method is called by the SetURL method to set the complete URL for the client instance.

See SetURL.

func (*Client[T]) SetURL

func (c *Client[T]) SetURL(scheme, host, baseUri, endpoint string) *Client[T]

SetURL sets the scheme, host, base URI, and endpoint for the client instance. These values will be used to construct the URL for the request.

The scheme parameter specifies the protocol scheme for the request, such as "http" or "https". The host parameter specifies the hostname or IP address of the server to send the request to. The baseUri parameter specifies the base URI for the API endpoint, such as "/v1" or "/api". The endpoint parameter specifies the endpoint for the API request, such as "/users" or "/posts/1".

Note: Support to use "-" or "" to ignore this parameter.

Example usage:

client.SetURL("https", "example.com", "/api/v1", "/users")

func (*Client[T]) SetUserAgent

func (c *Client[T]) SetUserAgent(ua string) *Client[T]

SetUserAgent sets the value of the "User-Agent" header for the request. It takes a `ua` parameter, which is a string representing the value of the "User-Agent" header. This method allows specifying the user agent for the request. It returns a pointer to the `Client` instance to allow for method chaining.

Example usage:

client.SetUserAgent("MyApp/1.0")

func (*Client[T]) Then

func (c *Client[T]) Then(cb CallbackOk[T]) *Client[T]

Then sets a callback function to be executed when the HTTP request is successful. The provided callback function cb is invoked only if no exception occurred during the request. The cb function is called with the result of the request as its argument. After executing the callback function, the client instance is returned.

func (*Client[T]) ToJson

func (c *Client[T]) ToJson(v any) error

func (*Client[T]) ToggleMode

func (c *Client[T]) ToggleMode() *Client[T]

func (*Client[T]) Unwrap

func (c *Client[T]) Unwrap() (*Client[T], string)

func (*Client[T]) UsePostHooks

func (c *Client[T]) UsePostHooks(funcs ...afterResponse[T])

UsePostHooks response Interceptor Middleware

func (*Client[T]) UsePreHooks

func (c *Client[T]) UsePreHooks(funcs ...beforeRequest[T])

UsePreHooks request interceptor middleware

type ClientFunc

type ClientFunc[T any] func(*Client[T])

func Lambda

func Lambda[T any](f func(*Client[T])) ClientFunc[T]

Lambda is a helper function that converts a function f into a ClientFunc[T]. It takes a function f as a parameter, which accepts a client instance and performs specific actions on it. The Lambda function wraps the provided function f and returns it as a ClientFunc[T]. The returned ClientFunc[T] can be used as an argument in the Optional method to apply the provided function to the client instance.

func WithDisabledRestMode deprecated

func WithDisabledRestMode[T any]() ClientFunc[T]

Deprecated: WithDisabledRestMode Close the restful api mode, the request body will become the content of the T generic. Notes: This method is useful if your response body is not a standard restful response format data! Instead: Please use the ToggleMode method.

func WithFilterSlash deprecated added in v0.1.4

func WithFilterSlash[T any](filterSlash bool) ClientFunc[T]

Deprecated: WithFilterSlash is a ClientFunc[T] function that sets the FilterSlash configuration of a client instance. It takes a boolean parameter filterSlash to enable or disable filtering of trailing slashes in URLs. When filterSlash is set to true, the client will remove any trailing slashes from the URLs it sends requests to. This can be useful in cases where the server treats URLs with and without trailing slashes differently. Note: that filtering slashes in URLs may affect the behavior of your requests, so use it carefully.

func WithIsDebug

func WithIsDebug[T any](isDebug bool) ClientFunc[T]

WithIsDebug is a ClientFunc[T] function that sets the IsDebug configuration of a client instance. It takes a boolean value isDebug.

func WithModifySuccessCode deprecated

func WithModifySuccessCode[T any](code int) ClientFunc[T]

Deprecated: WithModifySuccessCode sets the success return code for the client. The success code is used to identify successful responses. If not explicitly set, the default success code is 0.

func WithRegisterJsonLibrary added in v0.1.5

func WithRegisterJsonLibrary[T any](lib JSONLibrary) ClientFunc[T]

WithRegisterJsonLibrary is a ClientFunc[T] function that registers the json library for a client instance. You can choose the popular json parsing library independently. Note: Please implement the JSONLibrary interface definition yourself.

func WithSkipTLS

func WithSkipTLS[T any](skipTLS bool) ClientFunc[T]

WithSkipTLS is a ClientFunc[T] function that sets the SkipTLS configuration of a client instance. It takes a boolean value skipTLS as a parameter and returns a ClientFunc[T]. When applied to a client instance using the Optional method, it sets the SkipTLS configuration of the client to the provided value.

func WithTimeout

func WithTimeout[T any](timeout time.Duration) ClientFunc[T]

WithTimeout is a ClientFunc[T] function that configures the timeout duration for a client instance. It takes a time.Duration value timeout as a parameter and returns a ClientFunc[T]. When applied to a client instance using the Optional method, it configures the timeout duration based on the provided value. The timeout duration is capped to a minimum of TimeoutShort and a maximum of TimeoutLong.

func WithUseLogger

func WithUseLogger[T any](enabled bool) ClientFunc[T]

WithUseLogger is a ClientFunc[T] function that configures the usage of a logger for a client instance. It takes a boolean value enabled as a parameter and returns a ClientFunc[T]. When applied to a client instance using the Optional method, it configures the usage of a logger based on the provided value. If enabled is true, it configures a custom log formatter for the client's logger. If enabled is false, it does not configure a logger for the client.

type Config

type Config struct {
	Timeout       time.Duration
	SkipTLS       bool
	FilterSlash   bool
	IsDebug       bool
	Logger        *log.Logger
	IsRestMode    bool
	DefaultOkCode int
	JSONLoader    JSONLibrary
}

type Context

type Context struct {
	// client object
	HttpClient *http.Client

	// raw request
	Request *http.Request

	// raw response
	Response *Response
}

type Exception

type Exception struct {
	CodeLocation   string
	PanicError     error
	FailureReason  string
	OccurrenceTime timestamp
}

type ExecMethod

type ExecMethod[T any] func(method string) *RESTFulResp[T]

func Request

func Request[T any](path string, params H, data any, headers ...H) ExecMethod[T]

Request is a helper function that creates an ExecMethod function for making HTTP requests. It takes the path, query parameters, request payload, and optional headers as input. It returns an ExecMethod function that can be used to execute the specified HTTP method.

type GoJSONLibrary added in v0.1.5

type GoJSONLibrary struct{}

GoJSONLibrary is an implementation of the popular tripartite library go-json.

func (GoJSONLibrary) Marshal added in v0.1.5

func (l GoJSONLibrary) Marshal(v interface{}) ([]byte, error)

func (GoJSONLibrary) Unmarshal added in v0.1.5

func (l GoJSONLibrary) Unmarshal(data []byte, v interface{}) error

type H

type H = map[string]any

H is a type alias for an exported map[string]interface{}

type JSONLibrary added in v0.1.5

type JSONLibrary interface {
	Marshal(v interface{}) ([]byte, error)
	Unmarshal(data []byte, v interface{}) error
}

JSONLibrary Define the interface for serialization and deserialization of the json parsing library.

type Meta

type Meta struct {
	Method     string        // store the request method
	Url        string        // store the full url path
	Duration   time.Duration // time-consuming current request
	ReceivedAt time.Time     // store the timestamp indicating when the response was received
}

type NativeJSONLibrary added in v0.1.5

type NativeJSONLibrary struct{}

NativeJSONLibrary is the native implementation of encoding/json.

func (NativeJSONLibrary) Marshal added in v0.1.5

func (l NativeJSONLibrary) Marshal(v interface{}) ([]byte, error)

func (NativeJSONLibrary) Unmarshal added in v0.1.5

func (l NativeJSONLibrary) Unmarshal(data []byte, v interface{}) error

type RESTFulResp

type RESTFulResp[T any] struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data T      `json:"data,omitempty"`
}

type Response

type Response struct {
	R      *http.Response // all native objects
	Status int            // http response status code
	// contains filtered or unexported fields
}

type SMap

type SMap = map[string]string

SMap is a type alias for an exported map[string]string

Directories

Path Synopsis
examples
http-style command
requests-style command
try-catch-style command

Jump to

Keyboard shortcuts

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