Categorygithub.com/ogabrielrodrigues/rest
repositorypackage
1.0.4
Repository: https://github.com/ogabrielrodrigues/rest.git
Documentation: pkg.go.dev

# README


Rest Logo

GitHub Release GitHub License

Tired of having to do everything by hand every time you start a new go project with the chi router?

This set of pre-ready functions will help you save time and make you more productive.


Binding
Request body bind and validation with Validator.

import "github.com/ogabrielrodrigues/rest"

type Body struct {
  Name string `json:"name" validate:"required,min=2"`
  Age int `json:"age" validate:"required,min=1,max=140"`
}

func ExampleHandler(w http.ResponseWriter, r *http.Request) {
  body := Body{}

  if err := rest.Bind(r.Body, &body); err != nil {
    rest.JSON(w, err.Code, err)
    return
  }

  // Rest of your handler logic...
}

Error handling
Better handling of major http status errors.

import "github.com/ogabrielrodrigues/rest"

func ErrorHandler(w http.ResponseWriter, r *http.Request) {
  rest_error := rest.NewInternalServerErr(
    "this error occurred because the logic is not ready",
  )

  rest.JSON(w, rest_error.Code, rest_error)
}

// Output in JSON response:
{
  "message": "this error occurred because the logic is not ready",
  "code": 500,
  "error": "internal_server_error"
}

Response
Simple way to return data with ResponseWriter.

import (
  "net/http"
  "github.com/ogabrielrodrigues/rest"
)

func ResponseJSONHandler(w http.ResponseWriter, r *http.Request) {
  response := map[string]string{
    "message": "Thank you if you are reading this docs!!",
  }

  rest.JSON(w, http.StatusOK, response)
}

// Output in JSON response:
{
  "message": "Thank you if you are reading this docs!!",
}

Or prefer not to return data:

import (
  "net/http"
  "github.com/ogabrielrodrigues/rest"
)

func OnlyStatusHandler(w http.ResponseWriter, r *http.Request) {
  rest.End(w, http.StatusOK)
}

// Output in response headers:
HTTP/1.1 200 OK

Validation
Validate your request body or URL params with Validator.

import "github.com/ogabrielrodrigues/rest"

type Body struct {
  Name string `json:"name" validate:"required,min=2"`
  Age int `json:"age" validate:"required,min=1,max=140"`
}

func StructValidationHandler(w http.ResponseWriter, r *http.Request) {
  body := Body{}

  if err := rest.Validate.Struct(&body); err != nil {
    rest_error := rest.ValidateStructErr(err)
    rest.JSON(w, rest_error.Code, rest_error)
    return
  }

  // Rest of your handler logic...
}

Or validate one URL param:

import (
  "github.com/go-chi/chi/v5"
  "github.com/ogabrielrodrigues/rest"
)

func VarValidationHandler(w http.ResponseWriter, r *http.Request) {
  id := chi.URLParam(r, "id")

  if err := rest.Validate.Var(id, "uuid4"); err != nil {
    rest_error := rest.ValidateVarErr(err)
    rest.JSON(w, rest_error.Code, rest_error)
    return
  }

  // Rest of your handler logic...
}

Make with ❤️ by ogabrielrodrigues