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
+3.4k PHP : Convert CSV to JSON with YQL example
+5.6k Golang : Extract or copy items from map based on value
+19.2k Golang : Print out struct values in string format
+5.3k Android Studio : Indicate progression with ProgressBar example
+14.3k Golang : Convert PNG transparent background image to JPG or JPEG image
+7.1k Facebook : Getting the friends list with PHP return JSON format
+4.4k Golang : How to extract video or image files from html source code
+11.2k Golang : How to check for empty array string or string?
+7.3k Golang : Sort and reverse sort a slice of runes
+14.8k Golang : Example for RSA package functions
+3.5k Golang : If else example and common mistake
+2.6k Adding Skype actions such as call and chat into web page examples