How to Use HTTP Client Helpers in httpx for GET and POST Requests

The httpx package in jom-io/gorig provides centralized HTTP client helpers with built-in timeout handling, consistent error wrapping, and convenient methods for GET, POST JSON, POST form, and XML requests, including Gin context integration for automatic header forwarding.

The httpx package in the jom-io/gorig repository simplifies HTTP communication in Go applications by wrapping the standard net/http client with utilities for timeout management, error handling, and common request patterns. Whether you need to fetch JSON data from an external API or POST form data to a legacy endpoint, these HTTP client helpers in httpx reduce boilerplate while ensuring consistent error reporting through the repository's custom error types.

Core Features of the httpx Package

The httpx implementation in httpx/http.go centers on a shared *http.Client configured with a default timeout of 120 seconds. This client is accessed via getClient() and can be temporarily overridden using SetTimeOutTmp for specific requests requiring different timeout behavior.

All network errors are wrapped using the repository's *utils/errors.Error type (defined in utils/errors/err.go), providing stack traces and uniform error inspection across the codebase. For debugging, PostJSONResp utilizes the utils/logger package to emit outbound JSON payloads.

Making GET Requests with httpx Helpers

Simple GET with Query Parameters

The Get function constructs a URL with encoded query parameters and returns the response body as a string. This is the most basic HTTP client helper in httpx for retrieval operations.

package main

import (
	"fmt"

	"github.com/jom-io/gorig/httpx"
)

func main() {
	params := map[string]string{
		"q":    "golang",
		"page": "1",
	}
	body, err := httpx.Get("https://api.example.com/search", params)
	if err != nil {
		fmt.Println("request failed:", err)
		return
	}
	fmt.Println("response body:", body)
}

Implementation reference: Get builds the URL and uses http.Get – see lines 38‑60 in [httpx/http.go](https://github.com/jom-io/gorig/blob/master/httpx/http.go#L38-L60).

GET with Custom Headers

When you need to attach authentication tokens or content-type specifications, use GetHeader. This helper creates an http.NewRequest, attaches the provided header map, and executes the request with the shared client.

package main

import (
	"fmt"

	"github.com/jom-io/gorig/httpx"
)

func main() {
	headers := map[string]string{
		"Authorization": "Bearer abc123",
		"Accept":        "application/json",
	}
	body, err := httpx.GetHeader("https://api.example.com/profile", nil, headers)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println(body)
}

Implementation reference: GetHeader creates a request, sets each header, and executes it – see lines 72‑90 in the same file.

GET and Parse JSON Response

For APIs returning JSON, GetMap and GetMapHeader combine the retrieval logic with automatic unmarshaling into map[string]interface{}. These helpers eliminate manual JSON parsing boilerplate.

package main

import (
	"fmt"

	"github.com/jom-io/gorig/httpx"
)

func main() {
	data, err := httpx.GetMap("https://api.example.com/config", nil)
	if err != nil {
		fmt.Println("failed:", err)
		return
	}
	// data is a map[string]interface{}
	fmt.Printf("config version: %v\n", data["version"])
}

Implementation reference: GetMap calls Get then ParseJSON – see lines 93‑99.

Making POST Requests with httpx Helpers

POST Form Data

The PostForm helper handles application/x-www-form-urlencoded submissions, automatically encoding the parameter map into url.Values and using http.PostForm.

package main

import (
	"fmt"

	"github.com/jom-io/gorig/httpx"
)

func main() {
	form := map[string]string{
		"username": "alice",
		"password": "secret",
	}
	resp, err := httpx.PostForm("https://api.example.com/login", form)
	if err != nil {
		fmt.Println("login error:", err)
		return
	}
	fmt.Println("login response:", resp)
}

Implementation reference: PostForm builds url.Values and uses http.PostForm – lines 109‑127.

POST JSON Payloads

For REST APIs expecting JSON, PostJSON marshals your struct or map, sets the Content-Type: application/json header, and returns the parsed response as a map. The underlying PostJSONResp performs the actual request and logs the outbound payload for debugging.

package main

import (
	"fmt"

	"github.com/jom-io/gorig/httpx"
)

type Order struct {
	ItemID   string `json:"item_id"`
	Quantity int    `json:"quantity"`
}

func main() {
	order := Order{ItemID: "XYZ", Quantity: 3}
	result, err := httpx.PostJSON("https://api.example.com/orders", order)
	if err != nil {
		fmt.Println("order failed:", err)
		return
	}
	fmt.Printf("order ID: %v, status: %v\n", result["id"], result["status"])
}

Implementation reference: PostJSON → PostJSONResp (JSON marshal, POST, read body) → ParseJSON – see lines 129‑193.

POST with Custom Headers

When you need to attach authentication or request IDs to JSON POSTs, use PostJSONHeader. This variant accepts a header map and forwards it to the underlying request builder.

package main

import (
	"fmt"

	"github.com/jom-io/gorig/httpx"
)

func main() {
	payload := map[string]string{"msg": "hello"}
	headers := map[string]string{
		"Authorization": "Bearer xyz987",
	}
	resp, err := httpx.PostJSONHeader("https://api.example.com/echo", payload, headers)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println("server echoed:", resp)
}

Implementation reference: PostJSONHeader builds a request, injects the header map, and reuses PostJSONRespHeader – see lines 95‑104 and 153‑173.

POST XML Data

For legacy SOAP or XML-based services, PostXML manually constructs an XML document from a map and posts it with Content-Type: application/xml.

Implementation reference: PostXML is implemented in the same file alongside ParseXML for response handling.

Gin Integration and Request Context

Forwarding Authorization Headers

The httpx package provides Gin-aware helpers that simplify token propagation in microservice architectures. PostJSONByCtx extracts the Authorization header from the incoming Gin context and forwards it to the downstream service automatically.

func handler(c *gin.Context) {
	// Assume downstream expects the same Authorization token
	body, err := httpx.PostJSONByCtx(c, "https://api.example.com/forward", map[string]string{"data": "value"})
	if err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, body)
}

Implementation reference: PostJSONByCtx extracts Authorization from the Gin context and calls PostJSONHeader – see lines 206‑214 in httpx/http.go.

Similarly, GetByCtx performs the same header extraction for GET requests, ensuring consistent authentication propagation across service boundaries.

Timeout and Error Handling

Configuring Request Timeouts

All helpers rely on a shared *http.Client initialized with a default timeout of 120 seconds. You can temporarily override this duration for specific requests using SetTimeOutTmp, which modifies the client timeout for the next request only.

// Temporarily set a 30-second timeout for this request only
httpx.SetTimeOutTmp(30 * time.Second)
body, err := httpx.Get("https://slow-api.example.com/data", nil)

Understanding Error Wrapping

Every network or parsing error is wrapped using the repository's custom *utils/errors.Error type (defined in utils/errors/err.go). This provides stack traces and uniform error inspection across the codebase, allowing you to handle HTTP failures consistently whether they originate from connection timeouts, status code errors, or JSON parsing failures.

Summary

  • The httpx package in jom-io/gorig wraps Go's standard net/http with a shared client featuring a 120-second default timeout and centralized error handling via utils/errors.
  • GET requests are handled by Get (simple string response), GetHeader (custom headers), and GetMap/GetMapHeader (automatic JSON parsing into maps).
  • POST requests support form encoding (PostForm), JSON payloads (PostJSON, PostJSONHeader), and XML (PostXML), with PostJSONResp providing raw response access for debugging.
  • Gin integration via PostJSONByCtx and GetByCtx automatically propagates Authorization headers from incoming requests to downstream services.
  • All errors are wrapped in the repository's custom error type, and timeouts can be temporarily adjusted using SetTimeOutTmp.

Frequently Asked Questions

How do I add custom headers to a GET request using httpx?

Use the GetHeader function defined in httpx/http.go. Pass your headers as a map[string]string as the third argument. This helper creates an http.NewRequest, attaches your headers, and executes the request with the shared client.

What is the default timeout for HTTP requests in httpx?

The default timeout is 120 seconds. This is configured on the shared *http.Client returned by getClient(). You can temporarily override this for individual requests using SetTimeOutTmp(duration) before making the call.

How does httpx handle errors from HTTP requests?

All errors are wrapped using the repository's custom *utils/errors.Error type (from utils/errors/err.go). This includes connection failures, timeout errors, non-2xx status codes, and JSON/XML parsing errors. The wrapping preserves stack traces and provides a consistent interface for error inspection across the codebase.

Can I automatically forward authentication headers when using httpx in a Gin application?

Yes. Use PostJSONByCtx or GetByCtx (lines 206‑214 in httpx/http.go). These helpers extract the Authorization header from the incoming Gin context and automatically forward it to the downstream service, simplifying token propagation in microservice architectures.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →