httpio

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 8, 2023 License: MIT Imports: 8 Imported by: 6

README

httpio

The httpio package provides tools for decoding HTTP requests, decoding url parameters, and encoding HTTP responses in Go, complete with validation rules.

Getting Started

First, get the package by running:

go get github.com/cccteam/httpio

Decoder

The Decoder struct is used to decode and validate HTTP requests. It utilizes the json.NewDecoder() function to decode the HTTP request body into a provided struct.

Validation is handled by the Validator interface, which requires a Struct(s interface{}) error function. This function is expected to validate the struct s and return an error if the validation fails.

Example usage
type MyRequest struct {
    Field1 string `json:"field1" validate:"required"`
    Field2 int    `json:"field2" validate:"required,gt=0"`
}

v := validator.New()

func MyHandler(w http.ResponseWriter, r *http.Request) {
    req := &MyRequest{}
    validatorFunc :=  func(s interface{}) error {

        if err := v.Struct(s); err != nil {
            return err
        }

        return nil
    }

    decoder := httpio.NewDecoder(r, validatorFunc)
    if err := decoder.Decode(req); err != nil {
        // handle error
        return
    }
    // continue processing the request...
}

Encoder

The Encoder struct is used to encode HTTP responses. It has an implementation of the json.NewEncoder() function to encode a provided struct into the HTTP response body. The Encoder also allows for setting HTTP status codes and headers.

For usage of Encoder, please refer to the httpio package's source code.

Example usage

Here's an example of how to use Encoder:

type MyResponse struct {
    Message string `json:"message"`
    Code    int    `json:"code"`
}

func MyHandler(w http.ResponseWriter, r *http.Request) {
    // create response body
    responseBody := &MyResponse{
        Message: "Hello, world!",
        Code:    http.StatusOK,
    }

    // encode and send the response
    if err := httpio.NewEncoder(w).Ok(responseBody); err != nil {
        // handle error
        return
    }
}

The Encoder struct also provides methods to handle errors and encode HTTP error responses. Here's an example:

func MyHandler(w http.ResponseWriter, r *http.Request) {
    // some operation that may cause an error
    err := someOperation()
    if err != nil {
        // if the operation fails, return an Internal Server Error
        httpio.NewEncoder(w).InternalServerErrorWithMessage("This is what is returned in the response message", err)
        return
    }

    // if the operation is successful, proceed as normal...
}

Params

The Params() generic function serves as an enhancement to the chi router's parameters feature by decoding HTTP URL parameters into native Go types.

Currently the supported types are string, int, int64, float64, bool

Example usage
// given url: http://myapi.com/api/fileid/26
// and chi route of:          /api/fileid/{fileId}

func MyHandler(w http.ResponseWriter, r *http.Request) {
    param := Param[int64](r, "fileId")
    // param is parsed as type int64
    //
    // WithParams() middleware should be used to catch parsing errors
}

License

This project is licensed under the MIT License.

Documentation

Overview

httpio handles encoding and decoding for http i/o. This package is used to standardize request and response handling.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Param added in v0.0.2

func Param[T any](r *http.Request, param ParamType) (val T)

Param extracts the Param from the Request Context

func WithParams added in v0.0.2

func WithParams(next http.Handler) http.Handler

WithParams middleware is used to capture Param Parsing errors. They are returned as a http.StatusBadRequest status code with a message describing any parsing issue

Types

type Decoder

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

Decoder is a struct that can be used for decoding http requests and validating those requests

func NewDecoder

func NewDecoder(req *http.Request, validator ValidatorFunc) *Decoder

NewDecoder returns a pointer to a new Decoder struct

func (*Decoder) Decode

func (d *Decoder) Decode(request interface{}) error

Decode parses the http request body and validates it against the struct validation rules

type Encoder

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

Encoder is a struct that is used for encoding http responses

func NewEncoder

func NewEncoder(w http.ResponseWriter) *Encoder

NewEncoder returns a new Encoder to write to the ResponseWriter This encoder will write to the ResponseWriter using a json encoder.

func (*Encoder) BadRequest

func (e *Encoder) BadRequest(err error) error

BadRequest writes a http 400 status to the response header and returns the original error

func (*Encoder) BadRequestWithMessage

func (e *Encoder) BadRequestWithMessage(err error, message string) error

BadRequestWithMessage writes a bad request with a message body in the response

func (*Encoder) Conflict

func (e *Encoder) Conflict(err error) error

Conflict writes a 409 status to the response header and returns the original error

func (*Encoder) ConflictWithMessage

func (e *Encoder) ConflictWithMessage(err error, message string) error

ConflictWithMessage writes a 409 status to the response header and encodes a message in the response body

func (*Encoder) Forbidden

func (e *Encoder) Forbidden(err error) error

Forbidden writes a 403 status to the response header and returns the original error

func (*Encoder) ForbiddenWithMessage

func (e *Encoder) ForbiddenWithMessage(err error, message string) error

ForbiddenWithMessage returns a forbidden response with an error message

func (*Encoder) InternalServerError

func (e *Encoder) InternalServerError(err error) error

InternalServerError writes a 500 status to the response header and returns the original error

func (*Encoder) InternalServerErrorWithMessage

func (e *Encoder) InternalServerErrorWithMessage(err error, message string) error

InternalServerErrorWithMessage writes a 500 status to the response header and encodes a message in the response body

func (*Encoder) NotFound

func (e *Encoder) NotFound(err error) error

NotFound writes a 404 status to the response header and returns the original error

func (*Encoder) NotFoundWithMessage

func (e *Encoder) NotFoundWithMessage(err error, message string) error

NotFoundWithMessage writes a 404 status to the response header and encodes a message in the response body

func (*Encoder) Ok

func (e *Encoder) Ok(body interface{}) error

Ok returns a default http 200 status response with a body

func (*Encoder) ServiceUnavailable

func (e *Encoder) ServiceUnavailable(err error) error

ServiceUnavailable writes a 503 status to the response header and returns the original error

func (*Encoder) ServiceUnavailableWithMessage

func (e *Encoder) ServiceUnavailableWithMessage(err error, message string) error

ServiceUnavailableWithMessage writes a 503 status to the response header and encodes a message in the response body

func (*Encoder) StatusCode

func (e *Encoder) StatusCode(statusCode int, err error) error

StatusCode writes a statusCode to the response header and returns the original error

func (*Encoder) StatusCodeWithMessage

func (e *Encoder) StatusCodeWithMessage(statusCode int, err error, message string) error

StatusCodeWithMessage writes a statusCode and message to the response header and returns the original error

func (*Encoder) Unauthorized

func (e *Encoder) Unauthorized(err error) error

Unauthorized writes a 401 status to the response header and returns the original error

func (*Encoder) UnauthorizedWithMessage

func (e *Encoder) UnauthorizedWithMessage(err error, message string) error

UnauthorizedWithMessage returns an unauthorized response with an error message

type HTTPEncoder

type HTTPEncoder interface {
	// Encode is the call that is made to encode data into a response body and returns an error if it fails
	Encode(v interface{}) error
}

HTTPEncoder is an interface that is accepted when encoding http responses

type MessageResponse

type MessageResponse struct {
	Message string `json:"message,omitempty"`
}

MessageResponse holds a standard structure for http responses that carry a single message

type ParamType added in v0.0.2

type ParamType string

ParamType defines the type used to describe url Params

type ValidatorFunc

type ValidatorFunc func(s interface{}) error

ValidatorFunc is a function that validates s It returns an error if the validation fails

Jump to

Keyboard shortcuts

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