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
+6.9k Golang : Generate random elements without repetition or duplicate
+9.7k Golang : Overwrite previous output with count down timer
+20.5k Get file path of temporary file in Go
+34.8k Golang : Marshal and unmarshal json.RawMessage struct example
+25.5k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions
+8.5k Golang : Post data with url.Values{}
+3.7k PHP : Get client IP address
+5.5k Golang : get the current working directory of a running program
+8.9k Python : Convert IPv6 address to decimal and back to IPv6
+8.2k Swift : Convert (cast) String to Integer
+13.2k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+8.4k Golang : Convert int(year) to time.Time type