In order to create custom modules for pREST you need extends the router and register the custom new routes.
package main
import (
"net/http"
"github.com/prest/prest/cmd"
"github.com/prest/prest/config"
"github.com/prest/prest/config/router"
"github.com/prest/prest/middlewares"
)
func main() {
// Get pREST app
config.Load()
// Set Adapter postgres
postgres.Load()
middlewares.GetApp()
// Get pPREST router
r := router.Get()
// Register custom routes
r.HandleFunc("/ping", Pong).Methods("GET")
// Call pREST cmd
cmd.Execute()
}
func Pong(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Pong!"))
}
Using the previous sample we can create our middleware as a function and use that with GetApp() that returns a Negroni object.
package main
import (
"log"
"net/http"
"github.com/prest/prest/cmd"
"github.com/prest/prest/config"
"github.com/prest/prest/config/router"
"github.com/prest/prest/middlewares"
)
func main() {
config.Load()
// Set Adapter postgres
postgres.Load()
// Get pREST app
n := middlewares.GetApp()
// Register custom middleware
n.UseFunc(CustomMiddleware)
// Get pPREST router
r := router.Get()
// Register custom routes
r.HandleFunc("/ping", Pong).Methods("GET")
// Call pREST cmd
cmd.Execute()
}
func Pong(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Pong!"))
}
func CustomMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
log.Println("Calling custom middleware")
next(w, r)
}
In case needs reorder pREST middlewares.
package main
import (
"log"
"net/http"
"github.com/prest/prest/cmd"
"github.com/prest/prest/config"
"github.com/prest/prest/config/router"
"github.com/prest/prest/middlewares"
"github.com/urfave/negroni"
)
func main() {
config.Load()
// Set Adapter postgres
postgres.Load()
// Reorder middlewares
middlewares.MiddlewareStack = []negroni.Handler{
negroni.Handler(negroni.NewRecovery()),
negroni.Handler(negroni.NewLogger()),
negroni.Handler(middlewares.HandlerSet()),
negroni.Handler(negroni.HandlerFunc(CustomMiddleware)),
}
// Get pPREST router
r := router.Get()
// Register custom routes
r.HandleFunc("/ping", Pong).Methods("GET")
// Call pREST cmd
cmd.Execute()
}
func Pong(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Pong!"))
}
func CustomMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
log.Println("Calling custom middleware")
next(w, r)
}