Documentation
¶
Overview ¶
Package httputils defines common functions to manipulate the HTTP server.
Index ¶
- func DecodeRequestBody[T any](w http.ResponseWriter, r *http.Request, span trace.Span) (*T, bool)
- func GetRequestLogger(r *http.Request) *slog.Logger
- func GetURLParamInt64(r *http.Request, param string) (int64, error)
- func GetURLParamUUID(r *http.Request, param string) (uuid.UUID, error)
- func SetWriteResponseErrorAttribute(span trace.Span, err error)
- func WriteResponseError(w http.ResponseWriter, err error) error
- func WriteResponseJSON(w http.ResponseWriter, statusCode int, body any) error
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DecodeRequestBody ¶
func DecodeRequestBody[T any]( w http.ResponseWriter, r *http.Request, span trace.Span, ) (*T, bool)
DecodeRequestBody attempts to decode the HTTP request body into a value of type T.
Type Parameters:
T - The type into which the request body should be decoded. Typically a struct matching the expected JSON payload.
Parameters:
w - The http.ResponseWriter used to write error responses if decoding fails. r - The *http.Request containing the body to decode. span - The trace.Span used for recording tracing information and errors.
Returns:
*T - Pointer to the decoded value of type T, or nil if decoding fails. bool - True if decoding was successful, false otherwise.
Behavior:
- If the request body is missing (nil or http.NoBody), the function writes an HTTP error response (status 422 Unprocessable Entity) with message "request body is required".
- If the request body cannot be decoded as JSON into type T, the function writes an HTTP error response (status 422 Unprocessable Entity) with message "Invalid request body".
- In both error cases, sets the span status to error and returns (nil, false).
- On success, returns a pointer to the decoded value and true.
- The function may write HTTP responses in case of error, but does not write on success.
func GetRequestLogger ¶
GetRequestLogger gets the logger from request with request_id.
func GetURLParamInt64 ¶
GetURLParamInt64 gets a URL parameter and parses it as integer.
func GetURLParamUUID ¶
GetURLParamUUID gets a URL parameter and parses it as UUID.
func SetWriteResponseErrorAttribute ¶
SetWriteResponseErrorAttribute sets the error that happens when writing the HTTP response.
func WriteResponseError ¶
func WriteResponseError(w http.ResponseWriter, err error) error
WriteResponseError responds the error to the client.
func WriteResponseJSON ¶
func WriteResponseJSON(w http.ResponseWriter, statusCode int, body any) error
WriteResponseJSON writes response data with json encode. Returns the response size.
Types ¶
This section is empty.
Click to show internal directories.
Click to hide internal directories.