Documentation ¶
Overview ¶
Package gorestframework implements a simple library for creating REST endpoints in an easy way.
An example could be the following:
import ( "github.com/dennybiasiolli/gorestframework" "github.com/gorilla/mux" "github.com/jinzhu/gorm" ) // create the model definition // more info here: https://gorm.io/docs/models.html type Product struct { gorm.Model Code string Price uint } // create migration function func MigrateModels(db *gorm.DB) { db.AutoMigrate( // passing all desired models here &Product{}, ) } // create SetView function func SetViews(router *mux.Router) { gorestframework.View(&gorestframework.ViewInput{ Router: router, PathPrefix: "/products", ModelPtr: &Product{}, }) } func main() { // initializing database connection gorestframework.InitDbConn( "sqlite3", // DatabaseDialect, "test.db", // DatabaseConnectionString, MigrateModels, ) defer gorestframework.CloseDbConn() // start HTTP listener gorestframework.StartHTTPListener( true, // RouterActivateLog, true, // RouterUseCORS, views.SetViews, ) }
Index ¶
- Constants
- func AllowedHeaders(headers ...string) func(http.Handler) http.Handler
- func AllowedOrigin(origin string) func(http.Handler) http.Handler
- func CORS(methods ...string) func(http.Handler) http.Handler
- func CORSMiddleware(next http.Handler) http.Handler
- func CloseDbConn()
- func DbOperation(fn func(db *gorm.DB))
- func InitDbConn(databaseDialect string, connectionString string, ...)
- func IsDbInitialized() bool
- func JSONRespond(w http.ResponseWriter, data interface{}) error
- func JSONRespondWithStatus(w http.ResponseWriter, data interface{}, httpStatus int) error
- func LoggingMiddleware(next http.Handler) http.Handler
- func Respond(w http.ResponseWriter, r *http.Request, data interface{}) error
- func RespondWithStatus(w http.ResponseWriter, r *http.Request, data interface{}, httpStatus int) error
- func StartHTTPListener(activateLog bool, useCORS bool, fnSetViews func(*mux.Router))
- type ControllerOutput
- type ViewInput
- type ViewOutput
Constants ¶
const ( // JSONContentType is a constant defining the content type for json requests JSONContentType string = "application/json" )
Variables ¶
This section is empty.
Functions ¶
func AllowedHeaders ¶
AllowedHeaders is the middleware used to send Access-Control-Allow-Headers header
func AllowedOrigin ¶
AllowedOrigin is the middleware used to send Access-Control-Allow-Origin header
func CORS ¶
CORS is a middleware which enables Access-Control-Allow-Methods for specified methods. It also handles request method, denying it with a 405 (method not allowed) if it is not among the provided methods. example: router.Handle("/path", CORS(
http.MethodGet, http.MethodPatch, http.MethodPut, http.MethodDelete, )(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: srv.getDashboard(w, r) case http.MethodPatch, http.MethodPut: srv.editDashboard(w, r) case http.MethodDelete: srv.deleteDashboard(w, r) default: srv.RespondStatusError(w, r, http.StatusMethodNotAllowed) } }))
)
func CORSMiddleware ¶
CORSMiddleware is used to enable CORS capability for all hosts, PR are welcome!
func DbOperation ¶
DbOperation allows users to perform an operation on the active database.
func InitDbConn ¶
func InitDbConn( databaseDialect string, connectionString string, fnDbAutoMigrate func(db *gorm.DB), )
InitDbConn initialize a DB Connection using defined `databaseDialect` and `connectionString`. If defined, the `fnDbAutoMigrate` allows to execute auto-migration of database structure when the connection is opened. **Note**: don't forget to call `defer gorestframework.CloseDbConn()`
func IsDbInitialized ¶
func IsDbInitialized() bool
IsDbInitialized returns if database is already initialized
func JSONRespond ¶
func JSONRespond(w http.ResponseWriter, data interface{}) error
JSONRespond is a shortcut for JSONRespondWithStatus, using http.StatusOK as default status
func JSONRespondWithStatus ¶
func JSONRespondWithStatus(w http.ResponseWriter, data interface{}, httpStatus int) error
JSONRespondWithStatus writes to a http.ResponseWriter a specific `data` value in JSON format, using the passed httpStatus
func LoggingMiddleware ¶
LoggingMiddleware is used to log every request with Method and RequestURI
func Respond ¶
func Respond(w http.ResponseWriter, r *http.Request, data interface{}) error
Respond answers providing the correct content based on client accept header.
func RespondWithStatus ¶
func RespondWithStatus(w http.ResponseWriter, r *http.Request, data interface{}, httpStatus int) error
RespondWithStatus answers providing the correct content based on client accept header, with custom HTTP status.
func StartHTTPListener ¶
StartHTTPListener starts the HTTP Listener. HOST and PORT can be passed via ENV, unless the default are - HOST=localhost - PORT=8000
activateLog it's used to log requests to console useCORS enable CORS capability for all hosts, PR are welcome! fnSetViews is a callback function for configuring the mux.Router
Types ¶
type ControllerOutput ¶
type ControllerOutput struct { ModelPtr interface{} // pointer to the defined model GetAll func(w http.ResponseWriter, r *http.Request) // function for retreiving all records Get func(w http.ResponseWriter, r *http.Request) // function for retreiving a single record Post func(w http.ResponseWriter, r *http.Request) // function for adding a record Put func(w http.ResponseWriter, r *http.Request) // function for updating a record Patch func(w http.ResponseWriter, r *http.Request) // function for updating a record Delete func(w http.ResponseWriter, r *http.Request) // function for deleting a record }
ControllerOutput contains the output of the Controller function
func Controller ¶
func Controller(modelPtr interface{}) ControllerOutput
Controller returns a ControllerOutput containing all REST handlers
type ViewInput ¶
type ViewInput struct { Router *mux.Router // router used for adding the subroutes PathPrefix string // prefix where the subroutes will be added Controller *ControllerOutput // optional custom controller for the routes ModelPtr interface{} // model used for reading/writing data from/to database }
ViewInput contains the input of the View function
type ViewOutput ¶
type ViewOutput struct { Router *mux.Router // router used for adding the subroutes Subrouter *mux.Router // subrouter containing the subroutes PathPrefix string // prefix where the subroutes are added Controller ControllerOutput // controller used for the routes ModelPtr interface{} // model used for reading/writing data from/to database }
ViewOutput contains the output of the View function
func View ¶
func View( input *ViewInput, ) ViewOutput
View returns a ViewOutput containing all routes for a specific PathPrefix