Golang : Example of custom handler for Gorilla's Path usage.
In Gorilla WebToolkit's official documentation, the code fragment given in http://www.gorillatoolkit.org/pkg/mux#Route.Path does not show how to create custom handler to use together with Path()
function.
r := mux.NewRouter()
r.Path("/products/").Handler(ProductsHandler)
r.Path("/products/{key}").Handler(ProductsHandler)
r.Path("/articles/{category}/{id:[0-9]+}").
Handler(ArticleHandler)
This tutorial will demonstrate how to create custom handler for Path()
function. In this example, a custom http.Handler type must have a ServeHTTP method, otherwise the compiler will not compile the code.
package main
import (
"github.com/gorilla/mux"
"net/http"
"fmt"
)
type greetHandler struct {
gmux http.Handler
}
func (g *greetHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
//w.Write([]byte("Hello from greetHandler's ServeHTTP"))
name := mux.Vars(r)["name"]
w.Write([]byte(fmt.Sprintf("Hello %s from greetHandler's ServeHTTP! ", name)))
}
func main() {
mx := mux.NewRouter()
// bind gmux to mx(route)
ghandler := &greetHandler{gmux : mx}
mx.Path("/{name}").Handler(ghandler)
http.ListenAndServe(":8080", mx)
}
Hope this helps!
References :
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+11.3k Golang : Get absolute path to binary for os.Exec function with exec.LookPath
+10.8k Golang : Determine if time variables have same calendar day
+8.7k Golang : Check if user agent is a robot or crawler example
+11.5k Golang : Get terminal width and height example
+5.2k Golang : How to solve "too many .rsrc sections" error?
+21.4k Golang : simulate tail -f or read last line from log file example
+8.9k Golang : Use regular expression to get all upper case or lower case characters example
+3.2k Javascript : Empty an array example
+6.9k Golang : Configure Apache and NGINX to access your Go service example
+4.9k Facebook : How to force facebook to scrape latest URL link data?
+9.4k Golang : Underscore string example