apir

package
v1.16.63 Latest Latest
Warning

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

Go to latest
Published: Jan 21, 2026 License: GPL-3.0 Imports: 14 Imported by: 0

README ΒΆ

πŸ“¦ apir – Simple Go HTTP API Client

The apir package provides a clean and reusable HTTP client for interacting with REST APIs. It supports standard HTTP methods, automatic JSON (un)marshalling, customizable headers, and file uploads.


πŸ”§ Installation

go get github.com/MelloB1989/karma/apir

πŸ“˜ Usage

βœ… Initialize the Client
client := apir.NewAPIClient("https://api.example.com", map[string]string{
	"Authorization": "Bearer your_token",
	"Content-Type":  "application/json",
})

🧩 HTTP Methods

Each method sends a request and unmarshals the response JSON into responseStruct.

GET
err := client.Get("/endpoint", &responseStruct)
POST
err := client.Post("/endpoint", requestBody, &responseStruct)
PUT
err := client.Put("/endpoint", requestBody, &responseStruct)
DELETE
err := client.Delete("/endpoint", &responseStruct)
PATCH
err := client.Patch("/endpoint", requestBody, &responseStruct)
OPTIONS
err := client.Options("/endpoint", &responseStruct)
HEAD
err := client.Head("/endpoint", &responseStruct)
CONNECT
err := client.Connect("/endpoint", &responseStruct)
TRACE
err := client.Trace("/endpoint", &responseStruct)

πŸ“€ File Uploads

Upload a file via multipart/form-data.

err := client.UploadFile(
	"/upload",
	"fileField",                      // Form field name
	"./path/to/file.png",            // Local file path
	map[string]string{               // Optional additional fields
		"description": "Test upload",
	},
	&responseStruct,
)

🧰 Header Management

Add a Header
client.AddHeader("X-Custom-Header", "value")
Remove a Header
client.RemoveHeader("X-Custom-Header")

πŸ“₯ Internal Method

sendRequest

Used internally to make HTTP requests. Not required for general use, but available if needed:

responseBody, err := client.sendRequest("GET", "/endpoint", nil)

πŸ“Œ Notes

  • Automatically serializes requestBody to JSON.
  • Automatically deserializes response into provided struct.
  • Returns descriptive error if status code is not in the 2xx range.

πŸ›‘οΈ Example

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

client := apir.NewAPIClient("https://api.example.com", nil)

var user User
err := client.Get("/users/1", &user)
if err != nil {
	log.Fatal(err)
}

fmt.Printf("User: %+v\n", user)

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

This section is empty.

Functions ΒΆ

func IsHTTPError ΒΆ added in v1.16.31

func IsHTTPError(err error, statusCode int) bool

func TestAuthenticationScenarios ΒΆ added in v1.16.31

func TestAuthenticationScenarios(t *testing.T)

TestAuthenticationScenarios tests various authentication patterns

func TestErrorHandlingPatterns ΒΆ added in v1.16.31

func TestErrorHandlingPatterns(t *testing.T)

TestErrorHandlingPatterns tests common error handling patterns

func TestRESTfulScenarios ΒΆ added in v1.16.31

func TestRESTfulScenarios(t *testing.T)

TestRESTfulScenarios tests common RESTful API scenarios

func TestUsageExamples ΒΆ added in v1.16.31

func TestUsageExamples(t *testing.T)

TestUsageExamples demonstrates how to use the test helpers

Types ΒΆ

type APIClient ΒΆ

type APIClient struct {
	BaseURL        string
	Headers        map[string]string
	DebugMode      bool
	RawMode        bool
	Client         *http.Client
	RequestTimeout time.Duration
}

func NewAPIClient ΒΆ

func NewAPIClient(baseURL string, headers map[string]string, debug ...bool) *APIClient

func (*APIClient) AddHeader ΒΆ

func (client *APIClient) AddHeader(key, value string)

func (*APIClient) Connect ΒΆ

func (client *APIClient) Connect(endpoint string, responseStruct any) error

func (*APIClient) Delete ΒΆ

func (client *APIClient) Delete(endpoint string, responseStruct any) error

func (*APIClient) DeleteWithContext ΒΆ added in v1.16.31

func (client *APIClient) DeleteWithContext(ctx context.Context, endpoint string, responseStruct any) error

func (*APIClient) Get ΒΆ

func (client *APIClient) Get(endpoint string, responseStruct any) error

func (*APIClient) GetHeaders ΒΆ added in v1.16.31

func (client *APIClient) GetHeaders() map[string]string

func (*APIClient) GetWithContext ΒΆ added in v1.16.31

func (client *APIClient) GetWithContext(ctx context.Context, endpoint string, responseStruct any) error

func (*APIClient) Head ΒΆ

func (client *APIClient) Head(endpoint string, responseStruct any) error

func (*APIClient) Options ΒΆ

func (client *APIClient) Options(endpoint string, responseStruct any) error

func (*APIClient) Patch ΒΆ

func (client *APIClient) Patch(endpoint string, requestBody, responseStruct any) error

func (*APIClient) PatchWithContext ΒΆ added in v1.16.31

func (client *APIClient) PatchWithContext(ctx context.Context, endpoint string, requestBody, responseStruct any) error

func (*APIClient) Post ΒΆ

func (client *APIClient) Post(endpoint string, requestBody, responseStruct any) error

func (*APIClient) PostWithContext ΒΆ added in v1.16.31

func (client *APIClient) PostWithContext(ctx context.Context, endpoint string, requestBody, responseStruct any) error

func (*APIClient) Put ΒΆ

func (client *APIClient) Put(endpoint string, requestBody, responseStruct any) error

func (*APIClient) PutWithContext ΒΆ added in v1.16.31

func (client *APIClient) PutWithContext(ctx context.Context, endpoint string, requestBody, responseStruct any) error

func (*APIClient) RemoveHeader ΒΆ

func (client *APIClient) RemoveHeader(key string)

func (*APIClient) SetDebugMode ΒΆ added in v1.11.91

func (client *APIClient) SetDebugMode(debug bool)

func (*APIClient) SetHTTPClient ΒΆ added in v1.16.31

func (client *APIClient) SetHTTPClient(httpClient *http.Client)

func (*APIClient) SetRawMode ΒΆ added in v1.15.14

func (client *APIClient) SetRawMode(raw bool)

func (*APIClient) SetTimeout ΒΆ added in v1.16.31

func (client *APIClient) SetTimeout(timeout time.Duration)

func (*APIClient) Trace ΒΆ

func (client *APIClient) Trace(endpoint string, responseStruct any) error

func (*APIClient) UploadFile ΒΆ

func (client *APIClient) UploadFile(endpoint, fieldName, filePath string, additionalFields map[string]string, responseStruct any) error

func (*APIClient) UploadFileWithContext ΒΆ added in v1.16.31

func (client *APIClient) UploadFileWithContext(ctx context.Context, endpoint, fieldName, filePath string, additionalFields map[string]string, responseStruct any) error

func (*APIClient) UploadFiles ΒΆ added in v1.16.31

func (client *APIClient) UploadFiles(endpoint string, files map[string]string, additionalFields map[string]string, responseStruct any) error

func (*APIClient) UploadFilesWithContext ΒΆ added in v1.16.31

func (client *APIClient) UploadFilesWithContext(ctx context.Context, endpoint string, files map[string]string, additionalFields map[string]string, responseStruct any) error

func (*APIClient) UploadReader ΒΆ added in v1.16.31

func (client *APIClient) UploadReader(endpoint, fieldName, fileName string, reader io.Reader, additionalFields map[string]string, responseStruct any) error

func (*APIClient) UploadReaderWithContext ΒΆ added in v1.16.31

func (client *APIClient) UploadReaderWithContext(ctx context.Context, endpoint, fieldName, fileName string, reader io.Reader, additionalFields map[string]string, responseStruct any) error

type HTTPError ΒΆ added in v1.16.31

type HTTPError struct {
	StatusCode int
	Status     string
	Body       string
}

func GetHTTPError ΒΆ added in v1.16.31

func GetHTTPError(err error) (*HTTPError, bool)

func (*HTTPError) Error ΒΆ added in v1.16.31

func (e *HTTPError) Error() string

type MockServer ΒΆ added in v1.16.31

type MockServer struct {
	Server          *httptest.Server
	RequestCount    int
	LastRequest     *http.Request
	ResponseStatus  int
	ResponseBody    interface{}
	ResponseDelay   time.Duration
	ResponseHeaders map[string]string
	Handler         http.HandlerFunc
}

MockServer represents a configurable mock HTTP server

func NewMockServer ΒΆ added in v1.16.31

func NewMockServer() *MockServer

NewMockServer creates a new mock server with default settings

func (*MockServer) Close ΒΆ added in v1.16.31

func (m *MockServer) Close()

Close closes the mock server

func (*MockServer) Reset ΒΆ added in v1.16.31

func (m *MockServer) Reset()

Reset resets the mock server state

func (*MockServer) SetDelay ΒΆ added in v1.16.31

func (m *MockServer) SetDelay(delay time.Duration) *MockServer

SetDelay configures a response delay

func (*MockServer) SetHandler ΒΆ added in v1.16.31

func (m *MockServer) SetHandler(handler http.HandlerFunc) *MockServer

SetHandler sets a custom handler function

func (*MockServer) SetHeader ΒΆ added in v1.16.31

func (m *MockServer) SetHeader(key, value string) *MockServer

SetHeader adds a response header

func (*MockServer) SetResponse ΒΆ added in v1.16.31

func (m *MockServer) SetResponse(status int, body interface{}) *MockServer

SetResponse configures the mock server response

func (*MockServer) URL ΒΆ added in v1.16.31

func (m *MockServer) URL() string

URL returns the server URL

type TestHelper ΒΆ added in v1.16.31

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

TestHelper provides utility functions for testing

func NewTestHelper ΒΆ added in v1.16.31

func NewTestHelper(t *testing.T) *TestHelper

NewTestHelper creates a new test helper

func (*TestHelper) AssertEqual ΒΆ added in v1.16.31

func (h *TestHelper) AssertEqual(expected, actual interface{}, message string)

AssertEqual checks if two values are equal

func (*TestHelper) AssertError ΒΆ added in v1.16.31

func (h *TestHelper) AssertError(err error, message string)

AssertError fails the test if err is nil

func (*TestHelper) AssertFalse ΒΆ added in v1.16.31

func (h *TestHelper) AssertFalse(condition bool, message string)

AssertFalse checks if condition is false

func (*TestHelper) AssertNoError ΒΆ added in v1.16.31

func (h *TestHelper) AssertNoError(err error, message string)

AssertNoError fails the test if err is not nil

func (*TestHelper) AssertNotEqual ΒΆ added in v1.16.31

func (h *TestHelper) AssertNotEqual(expected, actual interface{}, message string)

AssertNotEqual checks if two values are not equal

func (*TestHelper) AssertTrue ΒΆ added in v1.16.31

func (h *TestHelper) AssertTrue(condition bool, message string)

AssertTrue checks if condition is true

Jump to

Keyboard shortcuts

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