Skip to content

Instantly share code, notes, and snippets.

@sandipb
Last active August 5, 2020 10:35
Show Gist options
  • Save sandipb/7428df65a89b824b54420ec4e1e67dae to your computer and use it in GitHub Desktop.
Save sandipb/7428df65a89b824b54420ec4e1e67dae to your computer and use it in GitHub Desktop.
Example code to use the Golang httprouter library
// Copied in parts as is from official docs
package main
import (
"fmt"
"net/http"
"os"
"strings"
"github.com/julienschmidt/httprouter"
)
func Index(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintln(w, "Hello there!")
}
func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}
func Welcome(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, "Welcome, %s to %s!\n",
ps.ByName("name"), strings.TrimLeft(ps.ByName("where"), "/"))
}
func Salut(w http.ResponseWriter, r *http.Request) {
ps := httprouter.ParamsFromContext(r.Context()) // ... (A)
fmt.Fprintf(w, "Salut, %s!\n", ps.ByName("name"))
}
func main() {
router := httprouter.New()
router.GET("/", Index)
router.GET("/hello/:name", Hello)
router.HandlerFunc("GET", "/salut/:name", Salut) // ... (B)
router.GET("/welcome/:name/*where", Welcome) // ... (C)
curDir, _ := os.Getwd()
router.ServeFiles("/files/*filepath", http.Dir(curDir)) // ... (D)
http.ListenAndServe("localhost:8888", router)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment