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
+17k Golang : How to generate QR codes?
+14.1k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+11.9k Golang : convert(cast) float to string
+36.1k Golang : Get file last modified date and time
+9.5k Golang : Generate EAN barcode
+11k Golang : Replace a parameter's value inside a configuration file example
+20.4k Golang : How to get own program name during runtime ?
+6.7k Golang : How to determine if request or crawl is from Google robots
+7.3k Golang : Dealing with postal or zip code example
+11.8k How to tell if a binary(executable) file or web application is built with Golang?
+6k AWS S3 : Prevent Hotlinking policy
+11.1k Golang : Create S3 bucket with official aws-sdk-go package