Documentation
¶
Overview ¶
Package rest provides the HTTP and REST related utilities for the application.
Index ¶
- Constants
- func BuildQuery(params map[string]string) string
- func DecodePathSegment(segment string) (string, error)
- func DownloadBytes(w http.ResponseWriter, r *http.Request, filename, contentType string, ...)
- func EncodePathSegment(segment string) string
- func GetClientIP(r *http.Request) string
- func GetIPVersion(ipStr string) int
- func IsHttpRequest(r *http.Request) bool
- func IsPrivateIP(ipStr string) bool
- func IsValidIP(ipStr string) bool
- func IsValidURL(raw string) bool
- func MakeHTTPRequest(ctx context.Context, client HttpClient, request RequestEntity) (responseObject map[string]interface{}, err error)
- func MaskIP(ipStr string) string
- func NormalizeIP(ip string) string
- func NormalizeURL(raw string) (string, error)
- func ParseQuery(query string) (map[string]string, error)
- func ReadJsonPayload(r *http.Request) (map[string]interface{}, error)
- func ValidateAndFetchGetParams(r *http.Request, keys map[string]reflect.Kind) (map[string]interface{}, error)
- func ValidateAndFetchPostParams(r *http.Request, keys map[string]reflect.Kind) (map[string]interface{}, error)
- type HttpClient
- type RequestEntity
- type Validator
Constants ¶
const ( // HTTP Headers HeaderAccept string = "Accept" HeaderAcceptEncoding string = "Accept-Encoding" HeaderAcceptLanguage string = "Accept-Language" HeaderCacheControl string = "Cache-Control" HeaderContentType string = "Content-Type" HeaderContentLength string = "Content-Length" HeaderContentEncoding string = "Content-Encoding" HeaderContentLanguage string = "Content-Language" HeaderContentDisposition string = "Content-Disposition" HeaderAuthorization string = "Authorization" HeaderUserAgent string = "User-Agent" HeaderConnection string = "Connection" HeaderPragma string = "Pragma" HeaderExpires string = "Expires" HeaderIfModifiedSince string = "If-Modified-Since" HeaderIfNoneMatch string = "If-None-Match" HeaderCookie string = "Cookie" HeaderAccessControlExposeHeaders string = "Access-Control-Expose-Headers" HeaderXForwardedFor string = "X-Forwarded-For" HeaderXRealIP string = "X-Real-Ip" HeaderXApiMinifier string = "X-API-Minify" HeaderXApiAuthToken string = "X-Api-Auth" + "Token" HeaderXContentTypeOptions string = "X-Content-Type-Options" HeaderXSignature string = "X-Auth-Signature" // Common Content-Type values ContentTypeJSON string = "application/json" ContentTypeXML string = "application/xml" ContentTypeZIP string = "application/zip" ContentTypeFormURLEncoded string = "application/x-www-form-urlencoded" ContentTypeMultipartFormData string = "multipart/form-data" ContentTypeMultipartMixed string = "multipart/mixed" ContentTypePlainText string = "text/plain" ContentTypeHTML string = "text/html" ContentTypeJavaScript string = "application/javascript" ContentTypeXJavaScript string = "application/x-javascript" ContentTypeTextJavaScript string = "text/javascript" ContentTypeCSS string = "text/css" ContentTypeJPEG string = "image/jpeg" ContentTypePNG string = "image/png" ContentTypeGIF string = "image/gif" ContentTypeOctetStream string = "application/octet-stream" XAPIMinifierValue string = "Y" )
Variables ¶
This section is empty.
Functions ¶
func BuildQuery ¶
BuildQuery takes a map of key-value pairs and constructs a URL-encoded query string. Keys and values are automatically escaped. Example: map{"q": "golang", "page": "1"} → "page=1&q=golang"
func DecodePathSegment ¶
DecodePathSegment unescapes a previously encoded path segment string. It reverses the effect of EncodePathSegment.
func DownloadBytes ¶
func DownloadBytes(w http.ResponseWriter, r *http.Request, filename, contentType string, data []byte)
DownloadBytes sends a byte slice as a downloadable file. - Keeps UTF-8 filenames, sanitizes only unsafe chars via SanitiseFilename - Sniffs Content-Type if not provided - Streams with range support using http.ServeContent - Exposes Content-Disposition header for JS to read (if needed)
Parameters:
- w: http.ResponseWriter to write the response to.
- r: Pointer to the http.Request that initiated the download.
- filename: The desired filename for the downloaded file.
- contentType: The MIME type of the file. If empty, it will be auto-detected.
- data: The byte slice containing the file data to be sent.
func EncodePathSegment ¶
EncodePathSegment safely escapes a path segment so it can be used in a URL without affecting its structure. For example, "a/b" becomes "a%2Fb".
func GetClientIP ¶
GetClientIP extracts the real client IP address from the HTTP request. It checks X-Forwarded-For and X-Real-IP headers before falling back to RemoteAddr.
func GetIPVersion ¶
GetIPVersion determines the IP version of the given address string. Returns 4 for IPv4, 6 for IPv6, and 0 if the IP is invalid or unrecognized.
func IsHttpRequest ¶
Determines and returns the flag if the current workflow is a HTTP request or not. This method is not full proof but will give you right results in all usual workflows.
func IsPrivateIP ¶
IsPrivateIP checks if the given IP address belongs to a private or reserved IP range. It supports both IPv4 (e.g., 10.0.0.0/8, 192.168.0.0/16) and IPv6 (e.g., fc00::/7) blocks.
Returns true if the IP is private, false otherwise. Returns false for invalid or unparseable IPs.
func IsValidIP ¶
IsValidIP checks whether the provided string is a valid IP address. It returns true for valid IPv4 or IPv6 addresses, and false otherwise.
func IsValidURL ¶
IsValidURL checks whether a string is a valid absolute URL, containing a scheme (e.g., http) and a host.
func MakeHTTPRequest ¶
func MakeHTTPRequest(ctx context.Context, client HttpClient, request RequestEntity) (responseObject map[string]interface{}, err error)
MakeHTTPRequest sends an HTTP request to a remote URL using the provided configuration and returns the parsed JSON response as a map. Before performing the real network call, it optionally attempts to return a stubbed response if a StubID is specified and stubbing is enabled.
The function supports GET requests with query parameters, arbitrary HTTP headers, request bodies, and graceful handling of various response scenarios.
Parameters:
- client: An HttpClient interface (generally *http.Client) used to execute the request.
- request: A RequestEntity defining the URL, HTTP method, headers, optional query parameters, request body, and an optional StubID.
Behavior:
- If request.StubID is non-empty, MakeHTTPRequest calls CallStub with the given ID. If stubbing is enabled and a matching stub is found, it immediately returns the stubbed response without making a real network call.
- If no stub response is returned (either because stubs are disabled, the StubID doesn't match any stub, or StubID is empty), MakeHTTPRequest proceeds to make a real HTTP call via client.Do(...) using the provided URL, method, headers, and body.
- On success, it attempts to parse the response body as JSON into a map[string]interface{}. The response is considered successful if it returns HTTP 200 (OK) or 201 (Created).
- If the response status code is not 200 or 201, MakeHTTPRequest returns an error with the response's status text.
- If parsing the JSON fails, it returns a JSON unmarshal error.
- If the HTTP call returns an error or a nil response, that error is returned.
Typical Usage:
request := RequestEntity{
Url: "https://api.example.com/data",
Method: http.MethodGet,
QueryParams: map[string][]string{
"filter": {"active"},
},
Headers: map[string]string{
"Authorization": "Bearer token_here",
},
StubID: "stub-1234", // Optional: if set and stubs match, will return stubbed response
}
result, err := MakeHTTPRequest(ctx, httpClient, request)
if err != nil {
log.Fatalf("Error making HTTP request: %v", err)
}
fmt.Printf("Received response: %v\n", result)
In testing or development:
- Set StubID and configure stubs via AddStub/CallStub to return predictable responses.
- Disable stubs or omit StubID to get real remote responses.
MakeHTTPRequest returns:
- (map[string]interface{}, error): On success, the parsed JSON response and no error; otherwise, an empty map and an error describing what went wrong.
func MaskIP ¶
MaskIP returns a partially masked (anonymized) version of the IP address. For IPv4, the last two octets are replaced with asterisks (e.g., 192.168.*.*). For IPv6, all but the first two segments are masked (e.g., abcd:1234::*). If the IP is invalid, it returns an empty string.
This is useful for logging or displaying user IPs without revealing the full address.
func NormalizeIP ¶
NormalizeIP trims spaces and normalizes the IP address string. It parses the input string and returns its canonical form. If the input is invalid, it returns an empty string.
Useful for cleaning up IP inputs before processing or logging.
func NormalizeURL ¶
NormalizeURL parses and returns a normalized version of the input URL, stripping any fragment (anchor) part like "#section".
func ParseQuery ¶
ParseQuery parses a URL-encoded query string into a map of key-value pairs. If a key has multiple values, only the first one is retained.
func ReadJsonPayload ¶
ReadJsonPayload reads and parses the JSON-encoded body of an http.Request into a map. This function is used to extract data from requests with JSON payloads.
Parameters:
- r: Pointer to the http.Request that contains the JSON body to be read.
Returns:
- A map of string to interface{} that holds the JSON data.
- An error if the body cannot be read or the JSON data is malformed.
func ValidateAndFetchGetParams ¶
func ValidateAndFetchGetParams(r *http.Request, keys map[string]reflect.Kind) (map[string]interface{}, error)
ValidateAndFetchGetParams extracts and validates GET parameters from the request based on the provided keys map. It ensures that each key exists and converts it to the specified data type in the map.
Parameters:
- r: Pointer to the http.Request from which GET parameters are to be extracted.
- keys: Map specifying each key and its expected data type using reflect.Kind.
Returns:
- A map containing the validated parameter values.
- An error if a parameter is missing or cannot be converted to the expected type.
func ValidateAndFetchPostParams ¶
func ValidateAndFetchPostParams(r *http.Request, keys map[string]reflect.Kind) (map[string]interface{}, error)
ValidateAndFetchPostParams extracts and validates POST parameters from the request based on the provided keys map. Similar to ValidateAndFetchGetParams, it parses form data and ensures each key is present and correctly typed.
Parameters:
- r: Pointer to the http.Request from which POST parameters are to be extracted.
- keys: Map specifying each key and its expected data type using reflect.Kind.
Returns:
- A map containing the validated parameter values.
- An error if form data cannot be parsed, a parameter is missing, or conversion fails.
Types ¶
type RequestEntity ¶
type RequestEntity struct {
Url string // Remote http(s) URL
Method string // HTTP method
Headers map[string]string // HTTP headers as a kv pair
QueryParams url.Values // HTTP query params
Body io.Reader // HTTP request payload/body
Timeout time.Duration // Timeout for the request
StubID string // ID of the stub to use for the request
}
RequestEntity is an input model for sending http requests to remote URL. This struct contains all required properties that are required to send a full-fledged HTTP request using CURL implementation.
type Validator ¶
type Validator struct {
// contains filtered or unexported fields
}
Validator holds a validator.Validate pointer that can be used to validate data according to struct tags.
func New ¶
func New() *Validator
New creates and returns a new Validator with a fresh instance of a validator.Validate.
func (*Validator) ValidateGET ¶
ValidateGET parses URL query parameters into a struct based on struct tags and performs validation. It supports conversion to string, int, and bool types based on the struct field types.
Parameters:
- params: url.Values containing the URL query parameters.
- obj: Pointer to the object that should receive the values.
Returns:
- An error if there is a mismatch in types or validation failures.
func (*Validator) ValidateJson ¶
ValidateJson decodes a JSON payload from an HTTP request and validates its structure. The function expects the JSON to match the structure of the obj parameter based on struct tags.
Parameters:
- r: Pointer to the http.Request containing the JSON body.
- obj: Pointer to the object structure the JSON should map to.
Returns:
- An error if the JSON is invalid or if it fails validation checks.
func (*Validator) ValidatePOST ¶
ValidatePOST parses form data from an HTTP POST request into a struct and performs validation. It supports similar type conversions and validations as ValidateGET.
Parameters:
- r: Pointer to the http.Request from which form data is parsed.
- obj: Pointer to the object that should receive the form values.
Returns:
- An error if the form data is invalid, cannot be parsed, or fails validation checks.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package apiresponse contains all the data models that are expected to be used by the application for core workflows.
|
Package apiresponse contains all the data models that are expected to be used by the application for core workflows. |
|
Package httpstub provides a mechanism to create and manage HTTP stubs for testing, development, and other scenarios where controlling outgoing HTTP responses is beneficial.
|
Package httpstub provides a mechanism to create and manage HTTP stubs for testing, development, and other scenarios where controlling outgoing HTTP responses is beneficial. |