Golang : HTTP Routing with Goji example
Alright, this tutorial will show you how to do HTTP routing with Carl Jackson a.k.a zenazn's Goji package. Pretty simple to use, but still require some digging to find the parameters from the web's context object.
Without much further ado ...
package main
import (
"flag"
"fmt"
"github.com/zenazn/goji"
"github.com/zenazn/goji/web"
"net/http"
)
func Home(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
func SayHello(c web.C, w http.ResponseWriter, r *http.Request) {
// get the name from web.C
// a request-local context object
// see https://github.com/zenazn/goji/blob/master/web/web.go
name := c.URLParams["name"]
w.Write([]byte(fmt.Sprintf("Hello %s !", name)))
}
func main() {
goji.Get("/", Home)
goji.Get("/:name", SayHello)
// goji default port number is 8000
// change to port number 8080
// with flag.Set
flag.Set("bind", ":8080")
goji.Serve()
}
Sample output :
http://localhost:8080/Grantt
Hello Grantt !
go run gojihttproute.go
2015/04/17 16:37:07.006907 Starting Goji on [::]:8080
2015/04/17 16:37:11.429155 [Sweets-Mac-Pro.lan/77dAC18tsA-000001] Started GET "/" from [::1]:56293
2015/04/17 16:37:11.429209 [Sweets-Mac-Pro.lan/77dAC18tsA-000001] Returning 200 in 15.382µs
2015/04/17 16:37:15.508627 [Sweets-Mac-Pro.lan/77dAC18tsA-000002] Started GET "/Grantt" from [::1]:56293
2015/04/17 16:37:15.508671 [Sweets-Mac-Pro.lan/77dAC18tsA-000002] Returning 200 in 12.433µs
NOTE : Nice color coded text logs spitted out by Goji! :-)
References :
See also : Golang : Pat multiplexer routing example
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.3k Golang : Derive cryptographic key from passwords with Argon2
+9.5k Golang : Sort and reverse sort a slice of integers
+5.8k Golang : Process non-XML/JSON formatted ASCII text file example
+7k Golang : Individual and total number of words counter example
+6.8k Golang : Use modern ciphers only in secure connection
+11.2k How to tell if a binary(executable) file or web application is built with Golang?
+10.4k Golang : Get UDP client IP address and differentiate clients by port number
+4.2k Adding Skype actions such as call and chat into web page examples
+6.5k Fix sudo yum hang problem with no output or error messages
+31.5k Golang : Validate email address with regular expression
+15.1k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+7.6k Golang : Grayscale Image