gosimplerest

package module
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2023 License: MIT Imports: 15 Imported by: 0

README

Go Simple Rest

This package provides an out of the box implementation of a rest api router for go, with simple configuration of the resources (tables in the database).

Currently contains implementation using sql as database, logrus as logger and go validator v10 as param validator.

The api will create endpoints for each resource configuration provided to the AddHandlers functions.

Currently supported routers are gorilla mux, gin, chi, echo and fiber.

To resource configuration can be see in the ./resource/resource.go file, in the Resource struct.

It creates the following routes (models are table names of the resources, converted to kebab case):

  • GET /model/{id}
  • GET /model
  • POST /model
  • PUT /model
  • PATCH /model
  • DELETE /model/{id}
  • HEAD /model
  • HEAD /model/{id}

The handlers created are standard http.HandlerFunc, so they can be used with any router.

Params from the url are passed to the handlers in the request context, using the GetRequestWithParams function.

Simple usage

First, import the package:

go get github.com/franciscoescher/gosimplerest

Bellow, a simple example of how to use the package. For a more complete example, see the ./examples/gin folder.

package main

import (
	"database/sql"
	"fmt"
	"os"

	"github.com/franciscoescher/gosimplerest"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"

	"github.com/go-sql-driver/mysql"
	"github.com/sirupsen/logrus"
	"gopkg.in/guregu/null.v3"
)

// Mysql Schema
/*
DROP TABLE IF EXISTS `users`;

CREATE TABLE `users` (
	`uuid` varchar(191) NOT NULL,
	`created_at` datetime(3) DEFAULT NULL,
	`deleted_at` datetime(3) DEFAULT NULL,
	`first_name` varchar(255) DEFAULT NULL,
	`phone` varchar(255) DEFAULT NULL,
	PRIMARY KEY (`uuid`)
);
*/

var UserResource = gosimplerest.Resource{
	Name:      "users",
	PrimaryKey: "uuid",
	Fields: map[string]gosimplerest.Field{
		"uuid":       {},
		"first_name": {},
		"phone":      {},
		"created_at": {},
		"deleted_at": {},
	},
	SoftDeleteField: null.NewString("deleted_at", true),
}

func main() {
	logger := logrus.New()

	logger.Info("starting application")

	db := getDB()
	defer db.Close()

	// create routes for rest api
	r := gin.Default()
	gosimplerest.AddGinHandlers(
		r,
		db,
		logger,
		validator.New(),
		[]gosimplerest.Resource{UserResource})

	logrus.Fatal(r.Run(":3333"))
}

func getDB() *sql.DB {
	c := mysql.Config{
		User:                 os.Getenv("DB_USER"),
		Passwd:               os.Getenv("DB_PASSWORD"),
		Net:                  "tcp",
		Addr:                 os.Getenv("DB_HOSTNAME") + ":" + os.Getenv("DB_PORT"),
		DBName:               os.Getenv("DB_SCHEMA"),
		ParseTime:            true,
		AllowNativePasswords: true,
	}

	db, err := sql.Open("mysql", c.FormatDSN())
	if err != nil {
		panic(err)
	}

	return db
}

Adding a new router type

To add a new router type, create a new file with the type of the router as name and that contains a function with the following signature:

func Add<name>Handlers(router <new type>, *sql.DB, l *logrus.Logger, v *validator.Validate, resources []Resource

This function should call the AddHandlers func, passing the AddRouteFunctions and AddParamFunc, which are a struct with functions that will add a route to the router, given a name and a handler (depending on the method), and a function that adds a parameter to a route url, respectively.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddChiHandlers added in v1.2.1

func AddChiHandlers(r *chi.Mux, d *sql.DB, l *logrus.Logger, v *validator.Validate, resources []resource.Resource) *chi.Mux

func AddEchoHandlers added in v1.2.1

func AddEchoHandlers(r *echo.Echo, d *sql.DB, l *logrus.Logger, v *validator.Validate, resources []resource.Resource) *echo.Echo

func AddFiberHandlers added in v1.2.1

func AddFiberHandlers(r *fiber.App, d *sql.DB, l *logrus.Logger, v *validator.Validate, resources []resource.Resource) *fiber.App

func AddGinHandlers added in v1.1.0

func AddGinHandlers(r *gin.Engine, d *sql.DB, l *logrus.Logger, v *validator.Validate, resources []resource.Resource) *gin.Engine

func AddGorillaMuxHandlers added in v1.1.0

func AddGorillaMuxHandlers(r *mux.Router, d *sql.DB, l *logrus.Logger, v *validator.Validate,
	resources []resource.Resource, mid func(h http.Handler) http.HandlerFunc) *mux.Router

func AddHandlers

func AddHandlers(d *sql.DB, l *logrus.Logger, v *validator.Validate, h AddRouteFunctions, apf AddParamFunc, resources []resource.Resource)

AddHandlers adds the routes to the router

func ChiHandlerWrapper added in v1.3.1

func ChiHandlerWrapper(h http.HandlerFunc) http.HandlerFunc

ChiHandlerWrapper wraps the handler function. It adds params to request context.

func EchoHandlerWrapper added in v1.3.1

func EchoHandlerWrapper(h http.HandlerFunc) echo.HandlerFunc

EchoHandlerWrapper converts a http.HandlerFunc to a echo.HandlerFunc It adds params to request context.

func FiberHandlerWrapper added in v1.3.1

func FiberHandlerWrapper(h http.HandlerFunc) fiber.Handler

FiberHandlerWrapper wraps the handler function to a fiber handler. It adds params to request context.

func GinHandlerWrapper added in v1.3.1

func GinHandlerWrapper(h http.HandlerFunc) gin.HandlerFunc

GinHandlerWrapper converts a http.HandlerFunc to a gin.HandlerFunc It adds params to request context.

func GorillaHandlerWrapper added in v1.3.1

func GorillaHandlerWrapper(mid func(h http.Handler) http.HandlerFunc, h http.HandlerFunc) http.HandlerFunc

GorillaHandlerWrapper wraps the handler function. It adds params to request context. If the middelware function is nil, it returns the handler

Types

type AddParamFunc added in v1.3.1

type AddParamFunc func(name string, param string) string

AddParamFunc is a function that adds a param to a url/endpoint. It should return the route with the param added. Example: /users + id -> /users/:id Each router/framework should implement this function.

type AddRouteFunc added in v1.3.1

type AddRouteFunc func(name string, h http.HandlerFunc)

AddRouteFunc is type of a function that adds a route to a router, with a given name and handler. It should also add the params to the handler. Each router/framework should implement this function.

func ChiAddRouteFunc added in v1.3.1

func ChiAddRouteFunc(f AddRouteFunc) AddRouteFunc

ChiAddRouteFunc uses the f function to add a route to the router, wrapping the handler to add params to request context.

func EchoAddRouteFunc added in v1.3.1

func EchoAddRouteFunc(f EchoAddRouteType) AddRouteFunc

EchoAddRouteFunc uses the f function to add a route to the router, wrapping the handler to add params to request context.

func FiberAddRouteFunc added in v1.3.1

func FiberAddRouteFunc(f FiberAddRouteType) AddRouteFunc

FiberAddRouteFunc uses the f function to add a route to the router, wrapping the handler to add params to request context.

func GinAddRouteFunc added in v1.3.1

func GinAddRouteFunc(f GinAddRouteType) AddRouteFunc

GinAddRouteFunc uses the f function to add a route to the router, wrapping the handler to add params to request context.

func GorillaAddRouteFunc added in v1.3.1

func GorillaAddRouteFunc(r *mux.Router, mid func(h http.Handler) http.HandlerFunc, method string) AddRouteFunc

GorillaAddRouteFunc is used to add a route to the router, using the given method. It adds the middleware function to the handler. It adds params to request context.

type AddRouteFunctions added in v1.3.1

type AddRouteFunctions struct {
	Post   AddRouteFunc
	Get    AddRouteFunc
	Put    AddRouteFunc
	Patch  AddRouteFunc
	Delete AddRouteFunc
	Head   AddRouteFunc
}

AddRouteFunctions is a struct that contains the functions to add routes to a router, one for each request method. Each router/framework should implement this struct.

type EchoAddRouteType added in v1.3.1

type EchoAddRouteType func(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route

EchoAddRouteType is the type of the function that echo.Echo uses to add routes to the router. Example: r.POST, r.GET...

type FiberAddRouteType added in v1.3.1

type FiberAddRouteType func(path string, handlers ...fiber.Handler) fiber.Router

FiberAddRouteType is the type of the function that fiber.App uses to add routes to the router. Example: r.Post, r.Get...

type GinAddRouteType added in v1.3.1

type GinAddRouteType func(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes

GinAddRouteType is the type of the function that gin.Engine uses to add routes to the router. Example: r.POST, r.GET...

Directories

Path Synopsis
chi
gin

Jump to

Keyboard shortcuts

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