cumi

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

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

Go to latest
Published: Oct 7, 2025 License: MIT Imports: 16 Imported by: 0

README

Cumi Http Requester

A simple HTTP client library for Go

Installation

go get github.com/sofyan48/cumi

Quick Start

Basic GET Request
package main

import (
    "fmt"
    "log"
    "github.com/sofyan48/cumi"
)

func main() {
    client := cumi.NewClient()
    resp, err := client.Http().Get("https://httpbin.org/get")
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Println("Status:", resp.Status)
    fmt.Println("Response:", resp.String())
}
SetSuccessResult - Auto JSON Parsing

Compared to standard net/http which requires manual steps:

// Traditional way with net/http
resp, err := http.Get("https://api.example.com/users/1")
if err != nil {
    return err
}
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
    return err
}

var user User
err = json.Unmarshal(body, &user)
if err != nil {
    return err
}

With requester SetSuccessResult, it becomes much simpler:

// With requester - auto parsing!
var user User
client := cumi.NewClient()
resp, err := client.Http().
    SetSuccessResult(&user).
    Get("https://api.example.com/users/1")

if err != nil {
    return err
}

if resp.IsSuccess() {
    // user is already populated with data!
    fmt.Printf("User: %+v\n", user)
}

Features

  • SetSuccessResult/SetErrorResult - Automatic response parsing
  • Zero external dependencies - Only uses Go standard library
  • Built-in retry mechanism with configurable backoff
  • Authentication support - Basic Auth, Bearer Token, API Key
  • Request/Response middleware for logging and preprocessing
  • File upload/download with progress callbacks
  • Debug mode for request/response logging
  • TLS configuration for custom certificates
  • Context support for timeout and cancellation
  • Form data and JSON request bodies
  • Query parameters and path parameters
  • Cookie management
  • Custom headers per request or globally
  • Tracing support with OpenTelemetry integration

Examples

GET Request with Auto JSON Parsing
package main

import (
    "fmt"
    "log"
    "github.com/sofyan48/requester"
)

type User struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
    Email string `json:"email"`
}

func main() {
    client := cumi.NewClient()
    var user User
    resp, err := client.Http().
        SetSuccessResult(&user).
        Get("https://jsonplaceholder.typicode.com/users/1")
    
    if err != nil {
        log.Fatal(err)
    }
    
    if resp.IsSuccess() {
        fmt.Printf("User: %+v\n", user)
    }
}
POST with JSON
func main() {
    client := cumi.NewClient()
    user := User{Name: "John", Email: "john@example.com"}
    
    resp, err := client.Http().
        SetBodyJSON(user).
        Post("https://httpbin.org/post")
    if err != nil {
        panic(err)
    }
    
    fmt.Println("Status:", resp.Status)
    fmt.Println("Response:", resp.String())
}
POST with Auto Result Binding
func main() {
    client := cumi.NewClient()
    user := User{Name: "John", Email: "john@example.com"}
    
    // Auto result binding with SetSuccessResult
    var result map[string]interface{}
    resp, err := client.Http().
        SetBodyJSON(user).
        SetSuccessResult(&result).
        Post("https://httpbin.org/post")
    
    if err != nil {
        panic(err)
    }
    
    if resp.IsSuccess() {
        fmt.Printf("Received JSON: %+v\n", result["json"])
    }
}
Error Handling with SetErrorResult
type APIError struct {
    Code    int    `json:"code"`
    Message string `json:"message"`
}

func main() {
    client := cumi.NewClient()
    var user User
    var apiError APIError
    
    resp, err := client.Http().
        SetSuccessResult(&user).
        SetErrorResult(&apiError).
        Get("https://api.example.com/users/999")
    
    if err != nil {
        log.Fatal(err)
    }
    
    if resp.IsSuccess() {
        fmt.Printf("User: %+v\n", user)
    } else {
        fmt.Printf("API Error: %+v\n", apiError)
    }
}
Client Configuration
client := cumi.NewClient().
    SetBaseURL("https://api.example.com").
    SetTimeout(30*time.Second).
    SetCommonHeader("Authorization", "Bearer your-token").
    SetRetryCount(3)

var users []User
resp, err := client.Http().
    SetSuccessResult(&users).
    Get("/users")

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client represents an HTTP client with chainable methods

func C

func C() *Client

C creates a new client (alias for NewClient)

func NewClient

func NewClient() *Client

NewClient creates a new HTTP client with default settings

func NewClientWithConfig

func NewClientWithConfig(config *Config) *Client

NewClientWithConfig creates a new HTTP client with provided configuration

func (*Client) Clone

func (c *Client) Clone() *Client

Clone creates a copy of the client

func (*Client) Delete

func (c *Client) Delete(url ...string) *Request

Delete creates a new DELETE request

func (*Client) DevMode

func (c *Client) DevMode() *Client

DevMode enables debug mode (alias for EnableDebug)

func (*Client) DisableAllowGetMethodPayload

func (c *Client) DisableAllowGetMethodPayload() *Client

DisableAllowGetMethodPayload disallows GET requests to have a body

func (*Client) DisableDebug

func (c *Client) DisableDebug() *Client

DisableDebug disables debug mode

func (*Client) DisableInsecureSkipVerify

func (c *Client) DisableInsecureSkipVerify() *Client

DisableInsecureSkipVerify disables skipping TLS certificate verification

func (*Client) EnableAllowGetMethodPayload

func (c *Client) EnableAllowGetMethodPayload() *Client

EnableAllowGetMethodPayload allows GET requests to have a body

func (*Client) EnableDebug

func (c *Client) EnableDebug() *Client

EnableDebug enables debug mode

func (*Client) EnableInsecureSkipVerify

func (c *Client) EnableInsecureSkipVerify() *Client

EnableInsecureSkipVerify enables skipping TLS certificate verification

func (*Client) Get

func (c *Client) Get(url ...string) *Request

Get creates a new GET request

func (*Client) GetClient

func (c *Client) GetClient() *http.Client

GetClient returns the underlying http.Client

func (*Client) GetTLSClientConfig

func (c *Client) GetTLSClientConfig() *tls.Config

GetTLSClientConfig returns the TLS configuration

func (*Client) Head

func (c *Client) Head(url ...string) *Request

Head creates a new HEAD request

func (*Client) Http

func (c *Client) Http() *Request

R creates a new request

func (*Client) OnAfterResponse

func (c *Client) OnAfterResponse(middleware ResponseMiddleware) *Client

OnAfterResponse adds a middleware that runs after receiving the response

func (*Client) OnBeforeRequest

func (c *Client) OnBeforeRequest(middleware RequestMiddleware) *Client

OnBeforeRequest adds a middleware that runs before sending the request

func (*Client) OnError

func (c *Client) OnError(handler ErrorHook) *Client

OnError sets the error handler

func (*Client) Options

func (c *Client) Options(url ...string) *Request

Options creates a new OPTIONS request

func (*Client) Patch

func (c *Client) Patch(url ...string) *Request

Patch creates a new PATCH request

func (*Client) Post

func (c *Client) Post(url ...string) *Request

Post creates a new POST request

func (*Client) Put

func (c *Client) Put(url ...string) *Request

Put creates a new PUT request

func (*Client) SetBaseURL

func (c *Client) SetBaseURL(baseURL string) *Client

SetBaseURL sets the base URL for the client

func (*Client) SetCommonCookies

func (c *Client) SetCommonCookies(cookies ...*http.Cookie) *Client

SetCommonCookies sets cookies that will be added to all requests

func (*Client) SetCommonErrorResult

func (c *Client) SetCommonErrorResult(err interface{}) *Client

SetCommonErrorResult sets the common error result type

func (*Client) SetCommonFormData

func (c *Client) SetCommonFormData(data map[string]string) *Client

SetCommonFormData sets form data that will be added to all requests

func (*Client) SetCommonHeader

func (c *Client) SetCommonHeader(key, value string) *Client

SetCommonHeader sets a header that will be added to all requests

func (*Client) SetCommonHeaders

func (c *Client) SetCommonHeaders(headers map[string]string) *Client

SetCommonHeaders sets multiple headers from a map

func (*Client) SetCommonPathParam

func (c *Client) SetCommonPathParam(key, value string) *Client

SetCommonPathParam sets a path parameter that will be used for URL replacement

func (*Client) SetCommonPathParams

func (c *Client) SetCommonPathParams(params map[string]string) *Client

SetCommonPathParams sets multiple path parameters from a map

func (*Client) SetCommonQueryParam

func (c *Client) SetCommonQueryParam(key, value string) *Client

SetCommonQueryParam sets a query parameter that will be added to all requests

func (*Client) SetCommonQueryParams

func (c *Client) SetCommonQueryParams(params map[string]string) *Client

SetCommonQueryParams sets multiple query parameters from a map

func (*Client) SetContext

func (c *Client) SetContext(ctx context.Context) *Client

SetContext sets the default context for all requests created from this client

func (*Client) SetJSONMarshal

func (c *Client) SetJSONMarshal(fn func(v interface{}) ([]byte, error)) *Client

SetJSONMarshal sets the JSON marshal function

func (*Client) SetJSONUnmarshal

func (c *Client) SetJSONUnmarshal(fn func(data []byte, v interface{}) error) *Client

SetJSONUnmarshal sets the JSON unmarshal function

func (*Client) SetProxy

func (c *Client) SetProxy(proxy func(*http.Request) (*url.URL, error)) *Client

SetProxy sets the proxy function

func (*Client) SetResultStateCheckFunc

func (c *Client) SetResultStateCheckFunc(fn func(*Response) ResultState) *Client

SetResultStateCheckFunc sets the function to check result state

func (*Client) SetRetryCondition

func (c *Client) SetRetryCondition(condition RetryConditionFunc) *Client

SetRetryCondition sets the condition for when to retry

func (*Client) SetRetryCount

func (c *Client) SetRetryCount(count int) *Client

SetRetryCount sets the number of retry attempts

func (*Client) SetRetryInterval

func (c *Client) SetRetryInterval(interval time.Duration) *Client

SetRetryInterval sets the interval between retries

func (*Client) SetTLSClientConfig

func (c *Client) SetTLSClientConfig(config *tls.Config) *Client

SetTLSClientConfig sets the TLS configuration

func (*Client) SetTimeout

func (c *Client) SetTimeout(timeout time.Duration) *Client

SetTimeout sets the request timeout

func (*Client) SetUserAgent

func (c *Client) SetUserAgent(userAgent string) *Client

SetUserAgent sets the User-Agent header for all requests

func (*Client) SetXMLMarshal

func (c *Client) SetXMLMarshal(fn func(v interface{}) ([]byte, error)) *Client

SetXMLMarshal sets the XML marshal function

func (*Client) SetXMLUnmarshal

func (c *Client) SetXMLUnmarshal(fn func(data []byte, v interface{}) error) *Client

SetXMLUnmarshal sets the XML unmarshal function

type Config

type Config struct {
	BaseURL           string
	Timeout           time.Duration
	Headers           map[string]string
	QueryParams       map[string]string
	PathParams        map[string]string
	UserAgent         string
	Debug             bool
	AllowGetPayload   bool
	RetryCount        int
	RetryInterval     time.Duration
	TLSConfig         *tls.Config
	Transport         http.RoundTripper
	BeforeRequest     []RequestMiddleware
	AfterResponse     []ResponseMiddleware
	RetryCondition    RetryConditionFunc
	ErrorHandler      ErrorHook
	OnError           ErrorHook
	CommonErrorResult interface{}
	ResultChecker     func(*Response) ResultState
}

Config holds default configuration for Client

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a default configuration

type ErrorHook

type ErrorHook func(*Client, *Request, *Response, error)

ErrorHook is called when an error occurs

type Request

type Request struct {
	// contains filtered or unexported fields
}

Request represents an HTTP request

func (*Request) Clone

func (r *Request) Clone() *Request

Clone creates a copy of the request

func (*Request) Context

func (r *Request) Context() context.Context

Context returns the request context

func (*Request) Delete

func (r *Request) Delete(url ...string) (*Response, error)

Delete executes a DELETE request

func (*Request) Do

func (r *Request) Do() (*Response, error)

Do is an alias for Execute

func (*Request) Execute

func (r *Request) Execute() (*Response, error)

Execute executes the request

func (*Request) Get

func (r *Request) Get(url ...string) (*Response, error)

Get executes a GET request

func (*Request) Head

func (r *Request) Head(url ...string) (*Response, error)

Head executes a HEAD request

func (*Request) Header

func (r *Request) Header() http.Header

Header returns the request headers

func (*Request) Method

func (r *Request) Method() string

Method returns the HTTP method

func (*Request) MustDelete

func (r *Request) MustDelete(url ...string) *Response

MustDelete executes a DELETE request and panics on error

func (*Request) MustExecute

func (r *Request) MustExecute() *Response

MustExecute executes the request and panics on error

func (*Request) MustGet

func (r *Request) MustGet(url ...string) *Response

MustGet executes a GET request and panics on error

func (*Request) MustHead

func (r *Request) MustHead(url ...string) *Response

MustHead executes a HEAD request and panics on error

func (*Request) MustOptions

func (r *Request) MustOptions(url ...string) *Response

MustOptions executes an OPTIONS request and panics on error

func (*Request) MustPatch

func (r *Request) MustPatch(url ...string) *Response

MustPatch executes a PATCH request and panics on error

func (*Request) MustPost

func (r *Request) MustPost(url ...string) *Response

MustPost executes a POST request and panics on error

func (*Request) MustPut

func (r *Request) MustPut(url ...string) *Response

MustPut executes a PUT request and panics on error

func (*Request) Options

func (r *Request) Options(url ...string) (*Response, error)

Options executes an OPTIONS request

func (*Request) Patch

func (r *Request) Patch(url ...string) (*Response, error)

Patch executes a PATCH request

func (*Request) Post

func (r *Request) Post(url ...string) (*Response, error)

Post executes a POST request

func (*Request) Put

func (r *Request) Put(url ...string) (*Response, error)

Put executes a PUT request

func (*Request) Send

func (r *Request) Send() (*Response, error)

Send is an alias for Execute

func (*Request) SetAuthToken

func (r *Request) SetAuthToken(token string) *Request

SetAuthToken is an alias for SetBearerToken

func (*Request) SetBasicAuth

func (r *Request) SetBasicAuth(username, password string) *Request

SetBasicAuth sets basic authentication

func (*Request) SetBearerToken

func (r *Request) SetBearerToken(token string) *Request

SetBearerToken sets the bearer token for authentication

func (*Request) SetBody

func (r *Request) SetBody(body interface{}) *Request

SetBody sets the request body

func (*Request) SetBodyBytes

func (r *Request) SetBodyBytes(body []byte) *Request

SetBodyBytes sets the request body from bytes

func (*Request) SetBodyJSON

func (r *Request) SetBodyJSON(body interface{}) *Request

SetBodyJSON sets the request body as JSON

func (*Request) SetBodyReader

func (r *Request) SetBodyReader(body io.Reader) *Request

SetBodyReader sets the request body from an io.Reader

func (*Request) SetBodyString

func (r *Request) SetBodyString(body string) *Request

SetBodyString sets the request body from a string

func (*Request) SetBodyXML

func (r *Request) SetBodyXML(body interface{}) *Request

SetBodyXML sets the request body as XML

func (*Request) SetContext

func (r *Request) SetContext(ctx context.Context) *Request

SetContext sets the context for the request

func (*Request) SetCookie

func (r *Request) SetCookie(cookie *http.Cookie) *Request

SetCookie sets a single cookie for the request

func (*Request) SetCookies

func (r *Request) SetCookies(cookies ...*http.Cookie) *Request

SetCookies sets cookies for the request

func (*Request) SetError

func (r *Request) SetError(result interface{}) *Request

SetError is an alias for SetErrorResult

func (*Request) SetErrorResult

func (r *Request) SetErrorResult(result interface{}) *Request

SetErrorResult sets the struct to unmarshal error response into

func (*Request) SetFormData

func (r *Request) SetFormData(data map[string]string) *Request

SetFormData sets form data for the request

func (*Request) SetFormDataFromValues

func (r *Request) SetFormDataFromValues(data url.Values) *Request

SetFormDataFromValues sets form data from url.Values

func (*Request) SetHeader

func (r *Request) SetHeader(key, value string) *Request

SetHeader sets a header for the request

func (*Request) SetHeaderVerbatim

func (r *Request) SetHeaderVerbatim(key, value string) *Request

SetHeaderVerbatim sets a header without canonicalizing the key

func (*Request) SetHeaders

func (r *Request) SetHeaders(headers map[string]string) *Request

SetHeaders sets multiple headers from a map

func (*Request) SetOutput

func (r *Request) SetOutput(filePath string) *Request

SetOutput sets the file path to save the response body

func (*Request) SetPathParam

func (r *Request) SetPathParam(key, value string) *Request

SetPathParam sets a path parameter for URL replacement

func (*Request) SetPathParams

func (r *Request) SetPathParams(params map[string]string) *Request

SetPathParams sets multiple path parameters from a map

func (*Request) SetQueryParam

func (r *Request) SetQueryParam(key, value string) *Request

SetQueryParam sets a query parameter for the request

func (*Request) SetQueryParams

func (r *Request) SetQueryParams(params map[string]string) *Request

SetQueryParams sets multiple query parameters from a map

func (*Request) SetQueryParamsFromValues

func (r *Request) SetQueryParamsFromValues(params url.Values) *Request

SetQueryParamsFromValues sets query parameters from url.Values

func (*Request) SetQueryString

func (r *Request) SetQueryString(query string) *Request

SetQueryString sets the query string directly

func (*Request) SetResult

func (r *Request) SetResult(result interface{}) *Request

SetResult is an alias for SetSuccessResult

func (*Request) SetSuccessResult

func (r *Request) SetSuccessResult(result interface{}) *Request

SetSuccessResult sets the struct to unmarshal successful response into

func (*Request) SetTracer

func (r *Request) SetTracer(tracer trace.Tracer, spanName string) *Request

SetTracer sets the tracer and span name for tracing HTTP request

func (*Request) SetUploadCallback

func (r *Request) SetUploadCallback(callback func(written int64, total int64)) *Request

SetUploadCallback sets a callback function for upload progress

func (*Request) SetUserAgent

func (r *Request) SetUserAgent(userAgent string) *Request

SetUserAgent sets the User-Agent header for this specific request

func (*Request) String

func (r *Request) String() string

String returns a string representation of the request

func (*Request) URL

func (r *Request) URL() string

URL returns the final request URL (after path parameter replacement)

func (*Request) Validate

func (r *Request) Validate() error

Validate validates the request

type RequestMiddleware

type RequestMiddleware func(*Client, *Request) error

RequestMiddleware defines a function that can modify a request before it's sent

type Response

type Response struct {
	Request  *Request
	Response *http.Response

	Err error

	// Embedded from http.Response for direct access
	Status     string
	StatusCode int
	Proto      string
	ProtoMajor int
	ProtoMinor int
	Header     http.Header
	// contains filtered or unexported fields
}

Response represents an HTTP response

func (*Response) Body

func (r *Response) Body() []byte

Body returns the response body as bytes

func (*Response) ContentType

func (r *Response) ContentType() string

ContentType returns the Content-Type header value

func (*Response) Cookies

func (r *Response) Cookies() []*http.Cookie

Cookies returns the cookies set by the server

func (*Response) Duration

func (r *Response) Duration() time.Duration

Duration returns the time taken for the request

func (*Response) Error

func (r *Response) Error() error

Error returns the error if any occurred during the request

func (*Response) IsError

func (r *Response) IsError() bool

IsError returns true if the response is an error (4xx or 5xx status code)

func (*Response) IsHTML

func (r *Response) IsHTML() bool

IsHTML returns true if the response content type is HTML

func (*Response) IsJSON

func (r *Response) IsJSON() bool

IsJSON returns true if the response content type is JSON

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

IsSuccess returns true if the response is successful (2xx status code)

func (*Response) IsText

func (r *Response) IsText() bool

IsText returns true if the response content type is plain text

func (*Response) IsXML

func (r *Response) IsXML() bool

IsXML returns true if the response content type is XML

func (*Response) JSON

func (r *Response) JSON(v interface{}) error

JSON unmarshals the response body into the provided interface using JSON

func (*Response) Location

func (r *Response) Location() string

Location returns the Location header value (useful for redirects)

func (*Response) ResultState

func (r *Response) ResultState() ResultState

ResultState returns the state of the response

func (*Response) Size

func (r *Response) Size() int64

Size returns the size of the response body in bytes

func (*Response) String

func (r *Response) String() string

String returns the response body as a string

func (*Response) Time

func (r *Response) Time() time.Time

Time returns the time when the response was received

func (*Response) XML

func (r *Response) XML(v interface{}) error

XML unmarshals the response body into the provided interface using XML

type ResponseMiddleware

type ResponseMiddleware func(*Client, *Response) error

ResponseMiddleware defines a function that can modify a response after it's received

type ResultState

type ResultState int

ResultState represents the state of the response

const (
	SuccessState ResultState = iota
	ErrorState
	UnknownState
)

type RetryConditionFunc

type RetryConditionFunc func(*Response, error) bool

RetryConditionFunc defines when a request should be retried

Directories

Path Synopsis
example
concurrency command
general command

Jump to

Keyboard shortcuts

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