req

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2025 License: MIT Imports: 9 Imported by: 26

README

req

Go Reference

A Go package providing utility functions for working with HTTP requests, making it easier to handle request parameters, headers, and other common HTTP operations.

Features

  • Retrieve values from GET, POST, and URL parameters with type conversion
  • Check for parameter existence in requests
  • Work with arrays and maps from request parameters
  • IP address utilities
  • Subdomain extraction
  • Trimmed value handling
  • Type-safe value retrieval with fallbacks

Installation

go get github.com/dracory/req

Quick Start

import "github.com/dracory/req"

// Get a value from request parameters
value := req.GetString(r, "key")

// Get a value with a default if not found
valueOr := req.GetStringOr(r, "key", "default")

// Check if a parameter exists
if req.Has(r, "key") {
    // Parameter exists
}

// Get all parameters from a request
allParams := req.GetAll(r)

Examples

Getting Values
// Get string value with empty string as default
username := req.GetString(r, "username")

// Get value with custom default
age := req.GetStringOr(r, "age", "18")

// Get trimmed value (whitespace removed)
searchTerm := req.GetStringTrimmed(r, "q")
Working with Arrays
// Get array of values
roles := req.GetArray(r, "roles", nil)

// Check if array contains a value (Go 1.21+)
hasAdmin := slices.Contains(roles, "admin")
if hasAdmin {
    // User has admin permission
}

IP Address Utilities
// Get client IP address
ip := req.GetIP(r)

// Check if IP is in a private range
if req.IsPrivateIP(ip) {
    // Handle private IP
}

Advanced (configurable):

// Use options to control precedence, trusted proxies, and extra headers
ip := req.GetIPWithOptions(r, req.IPOptions{
    PreferForwardedFor:        true, // check X-Forwarded-For before X-Real-IP
    TrustedProxies:            []string{"127.0.0.1/32", "10.0.0.0/8", "::1/128"},
    AdditionalHeaders:         []string{"CF-Connecting-IP", "True-Client-IP"},
    Validate:                  true,  // ensure candidates parse as IPs
    ReturnPrivateIfAllPrivate: true,  // when no public IP in XFF
})
Subdomain Handling
// Extract subdomain from host
subdomain := req.GetSubdomain(r) // returns "api" for host like api.example.com

Available Functions

Request Parameter Handling
  • GetString(r *http.Request, key string) string - Returns the value of a GET or POST parameter
  • GetStringOr(r *http.Request, key string, defaultValue string) string - Returns a value with a fallback if not found
  • GetStringTrimmed(r *http.Request, key string) string - Returns a trimmed (whitespace removed) value
  • GetStringTrimmedOr(r *http.Request, key string, defaultValue string) string - Returns a trimmed value with a fallback
Parameter Existence Checking
  • Has(r *http.Request, key string) bool - Checks if a parameter exists in GET or POST
  • HasGet(r *http.Request, key string) bool - Checks if a GET parameter exists
  • HasPost(r *http.Request, key string) bool - Checks if a POST parameter exists
Array Operations
  • GetArray(r *http.Request, key string, defaultValue []string) []string - Gets an array of values from request parameters
Map Operations
  • GetMap(r *http.Request, key string) map[string]string - Gets a map from request parameters
  • GetMaps(r *http.Request, key string, defaultValue []map[string]string) []map[string]string - Gets an array of maps from request parameters
IP Address Utilities
  • GetIP(r *http.Request) string - Gets the client's IP address
  • GetIPWithOptions(r *http.Request, opts IPOptions) string - Gets the client's IP with configurable precedence, trusted proxies, and headers
  • IsPrivateIP(ip string) bool - Checks if an IP address is in a private range
Subdomain Handling
  • GetSubdomain(r *http.Request) string - Extracts the subdomain from the request hostname
Request Data
  • GetAll(r *http.Request) url.Values - Gets all request parameters (GET and POST combined)
  • GetAllGet(r *http.Request) url.Values - Gets all GET parameters
  • GetAllPost(r *http.Request) url.Values - Gets all POST parameters

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AllGet

func AllGet(r *http.Request) url.Values

AllGet returns all GET request variables as a url.Values object. Deprecated: prefer GetAllGet for naming consistency. Kept to match documentation.

func AllPost

func AllPost(r *http.Request) url.Values

AllPost returns all POST request variables as a url.Values object. Deprecated: prefer GetAllPost for naming consistency. Kept to match documentation.

func GetAll

func GetAll(r *http.Request) url.Values

GetAll returns all request variables (both GET and POST) as a url.Values object

Parameters:

  • r *http.Request: HTTP request

Returns:

  • url.Values: all request variables from both GET and POST

func GetAllGet

func GetAllGet(r *http.Request) url.Values

GetAllGet returns all GET request variables as a url.Values object

Parameters:

  • r *http.Request: HTTP request

Returns:

  • url.Values: GET request variables

func GetAllPost

func GetAllPost(r *http.Request) url.Values

GetAllPost returns all POST request variables as a url.Values object Note: This will only work for application/x-www-form-urlencoded and multipart/form-data

Parameters:

  • r *http.Request: HTTP request

Returns:

  • url.Values: POST request variables

func GetArray

func GetArray(r *http.Request, key string, defaultValue []string) []string

GetArray retrieves values from the request that match the given key in various formats: 1. Direct match (key=value1&key=value2) 2. Array notation (key[]=value1&key[]=value2) 3. Numbered notation (key[0]=value1&key[1]=value2)

Parameters:

  • r *http.Request: HTTP request containing the form data
  • key string: the key to look up in the form data
  • defaultValue []string: value to return if key is not found

Returns:

  • []string: array of values for the key, or defaultValue if not found

func GetBool

func GetBool(r *http.Request, key string) bool

GetBool returns the bool value of a request parameter. Returns false if the key is missing or conversion fails.

func GetBoolOr

func GetBoolOr(r *http.Request, key string, defaultValue bool) bool

GetBoolOr returns the bool value of a request parameter or defaultValue if the key is missing or conversion fails.

func GetFloat64

func GetFloat64(r *http.Request, key string) float64

GetFloat64 returns the float64 value of a request parameter. Returns 0 if the key is missing or conversion fails.

func GetFloat64Or

func GetFloat64Or(r *http.Request, key string, defaultValue float64) float64

GetFloat64Or returns the float64 value of a request parameter or defaultValue if the key is missing or conversion fails.

func GetIP

func GetIP(r *http.Request) string

GetIP gets the IP address for the user by checking X-REAL-IP, X-FORWARDED-FOR headers, and finally falling back to RemoteAddr. For X-FORWARDED-FOR, it returns the first non-private IP address in the chain, or the last IP if all are private.

func GetIPWithOptions

func GetIPWithOptions(r *http.Request, opts IPOptions) string

GetIPWithOptions determines the client IP using the provided options.

func GetInt

func GetInt(r *http.Request, key string) int

GetInt returns the int value of a request parameter. Returns 0 if the key is missing or conversion fails.

func GetInt64

func GetInt64(r *http.Request, key string) int64

GetInt64 returns the int64 value of a request parameter. Returns 0 if the key is missing or conversion fails.

func GetInt64Or

func GetInt64Or(r *http.Request, key string, defaultValue int64) int64

GetInt64Or returns the int64 value of a request parameter or defaultValue if the key is missing or conversion fails.

func GetIntOr

func GetIntOr(r *http.Request, key string, defaultValue int) int

GetIntOr returns the int value of a request parameter or defaultValue if the key is missing or conversion fails.

func GetMap

func GetMap(r *http.Request, key string) map[string]string

GetMap returns a map from the request

Parameters:

  • r *http.Request: HTTP request
  • key string: key to get map for

Returns:

  • map[string]string: map for key

func GetMaps

func GetMaps(r *http.Request, key string, defaultValue []map[string]string) []map[string]string

GetMaps parses an array of maps from request parameters with the given key prefix. Supported formats:

  • key[mapKey][] = value (auto-numbered rows)
  • key[outer][inner] = value (two-level keys; uses the inner key as the map key)

Parameters:

  • r: The HTTP request
  • key: The base key to look for in the request
  • defaultValue: The default value to return if no matching parameters are found

Returns:

  • []map[string]string: An array of maps containing the parsed values

func GetString

func GetString(r *http.Request, key string) string

GetString returns a POST or GET key, or empty string if not exists

Parameters:

  • r *http.Request: HTTP request
  • key string: key to get value for

Returns:

  • string: value for key, or empty string if not exists

func GetStringOr

func GetStringOr(r *http.Request, key string, defaultValue string) string

GetStringOr returns a POST or GET key, or the provided default value if the key does not exist or its value is an empty string.

Parameters:

  • r *http.Request: HTTP request
  • key string: key to get value for
  • defaultValue string: default value to return if key does not exist or is empty

Returns:

  • string: value for key, or default value if key doesn't exist or is empty

func GetStringTrimmed

func GetStringTrimmed(r *http.Request, key string) string

GetStringTrimmed returns a POST or GET key with leading and trailing whitespace removed. Returns an empty string if the key does not exist.

Parameters:

  • r *http.Request: HTTP request
  • key string: key to get value for

Returns:

  • string: trimmed value for key, or empty string if not exists

func GetStringTrimmedOr

func GetStringTrimmedOr(r *http.Request, key string, defaultValue string) string

GetStringTrimmedOr returns a POST or GET key with leading and trailing whitespace removed. If the resulting value is empty or the key doesn't exist, returns the provided default value. Note: The default value is also trimmed of leading and trailing whitespace.

Parameters:

  • r *http.Request: HTTP request
  • key string: key to get value for
  • defaultValue string: default value to return if key doesn't exist or value is empty after trimming

Returns:

  • string: trimmed value for key, or trimmed default value if the key doesn't exist or value is empty after trimming

func GetSubdomain

func GetSubdomain(r *http.Request) string

GetSubdomain finds the subdomain in the host of the given request.

Business logic: - extract the host from the request - if the host is "localhost", return an empty string - if there is no dot in the host, return an empty string - otherwise, return the part of the host before the first dot

Parameters:

  • r (*http.Request): The HTTP request from which to extract the subdomain.

Returns:

  • string: the subdomain, or an empty string if none found.

func Has

func Has(r *http.Request, key string) bool

Has returns true if GET or POST key exists

Parameters:

  • r *http.Request: HTTP request
  • key string: key to check if exists

Returns:

  • bool: true if key exists

func HasGet

func HasGet(r *http.Request, key string) bool

HasGet returns true if GET key exists

Parameters:

  • r *http.Request: HTTP request
  • key string: key to check if exists

Returns:

  • bool: true if key exists

func HasPost

func HasPost(r *http.Request, key string) bool

HasPost returns true if POST key exists

Parameters:

  • r *http.Request: HTTP request
  • key string: key to check if exists

Returns:

  • bool: true if key exists

func IsPrivateIP

func IsPrivateIP(ipStr string) bool

IsPrivateIP checks if an IP address is in a private network range. It supports both IPv4 and IPv6 addresses.

Parameters:

  • ipStr: The IP address to check (can be in string format)

Returns:

  • bool: true if the IP is in a private range, false otherwise

Types

type IPOptions

type IPOptions struct {
	PreferForwardedFor        bool
	TrustedProxies            []string
	AdditionalHeaders         []string
	Validate                  bool
	ReturnPrivateIfAllPrivate bool // used when no TrustedProxies specified and scanning XFF
}

IPOptions configures how GetIPWithOptions determines the client IP.

Behavior overview:

  • Header precedence: When PreferForwardedFor is true, X-Forwarded-For is checked before X-Real-IP. Otherwise, X-Real-IP is checked first (same as GetIP).
  • Trusted proxies: If TrustedProxies is provided (CIDRs or single IPs), the client IP is taken as the first address in X-Forwarded-For that is NOT within the trusted list. If all are trusted, the last address is returned.
  • Additional headers: AdditionalHeaders are checked in order before falling back to RemoteAddr.
  • Validation: If Validate is true, candidate IPs must parse via net.ParseIP; invalid values are skipped.

Note: This function does not mutate request state and does not perform DNS lookups. It relies entirely on headers/RemoteAddr and the provided options.

Example trusted proxies list:

[]string{"127.0.0.1/32", "10.0.0.0/8", "::1/128"}

Common additional headers:

[]string{"CF-Connecting-IP", "True-Client-IP"}

If you want the simple behavior, use GetIP(). Use GetIPWithOptions when behind load balancers/reverse-proxies and you control trust.

Jump to

Keyboard shortcuts

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