More details in my blogpost at https://blog.sandipb.net/2020/08/05/notes-on-the-httprouter-golang-library/
Last active
August 5, 2020 10:35
-
-
Save sandipb/7428df65a89b824b54420ec4e1e67dae to your computer and use it in GitHub Desktop.
Example code to use the Golang httprouter library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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