Golang : Denco multiplexer example
Kinda free today to test out couple of Golang's web multiplexers. One of the most interesting multiplexers that I've tried is the Denco package. It is pretty straightforward to use and you can get the posted values easily with denco.Params
.
Redirecting to different functions based on URL path patterns can be done easily too with the []denco.Record
type. (see http://godoc.org/github.com/naoina/denco#Record)
This example will focus on the multiplexer section of Denco and it is taken with slight modification from https://github.com/naoina/denco
.
package main
import (
"fmt"
"github.com/naoina/denco"
"net/http"
)
func Home(w http.ResponseWriter, r *http.Request, params denco.Params) {
w.Write([]byte("Hello, World!"))
}
func HelloUser(w http.ResponseWriter, r *http.Request, params denco.Params) {
w.Write([]byte(fmt.Sprintf("Hello, %s!", params.Get("name"))))
}
func main() {
mx := denco.NewMux()
handler, err := mx.Build([]denco.Handler{
mx.GET("/", Home),
mx.GET("/hellouser/:name", HelloUser),
mx.POST("/hellouser/:name", HelloUser),
})
if err != nil {
panic(err)
}
http.ListenAndServe(":8080", handler)
}
Sample output :
http://localhost:8080/hellouser/Adam
Hello, Adam!
Reference :
See also : Golang : Routes multiplexer routing example with regular expression control
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
+8.1k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+8.4k Golang : Accept any number of function arguments with three dots(...)
+18.6k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+4.5k Python : Find out the variable type and determine the type with simple test
+8k Golang : Implementing class(object-oriented programming style)
+11.8k Golang : convert(cast) string to integer value
+26.2k Golang : Force your program to run with root permissions
+16k Golang : Test floating point numbers not-a-number and infinite example
+7.6k Golang : Gomobile init produce "iphoneos" cannot be located error
+6.4k Golang : Get expvar(export variables) to work with multiplexer
+14k Golang : How to filter a map's elements for faster lookup
+18.7k Golang : Get host name or domain name from IP address