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
+31.7k Golang : Validate email address with regular expression
+13.1k Golang : error parsing regexp: invalid or unsupported Perl syntax
+8.2k Golang : How to check if input string is a word?
+10.4k Golang : Bubble sort example
+6k Golang : Calculate US Dollar Index (DXY)
+10.1k Fix ERROR 1045 (28000): Access denied for user 'root'@'ip-address' (using password: YES)
+46k Golang : Marshal and unmarshal json.RawMessage struct example
+9.9k Golang : Bcrypting password
+6.8k Golang : Levenshtein distance example
+13.5k Golang : Check if an integer is negative or positive
+26k Golang : Get executable name behind process ID example
+11.2k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions