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
+6.5k Golang : Add build version and other information in executables
+5.2k Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?
+5.2k Golang : Warp text string by number of characters or runes example
+17.7k Golang : Delete item from slice based on index/key position
+8.6k Golang : How to tokenize source code with text/scanner package?
+3.3k Chrome : How to block socketloop.com links in Google SERP?
+51.7k Golang : Unmarshal JSON from http response
+8.6k Golang : Allow Cross-Origin Resource Sharing request
+8k Golang : Resumable upload to Google Drive(RESTful) example
+9.3k Golang : Find age or leap age from date of birth example
+5.7k Golang : Lock executable to a specific machine with unique hash of the machine
+3.6k HTTP common errors and their meaning explained