Skip to content

Instantly share code, notes, and snippets.

@subnut
Last active August 1, 2022 15:03
Show Gist options
  • Save subnut/6e7630bd948650487a3164d024e89670 to your computer and use it in GitHub Desktop.
Save subnut/6e7630bd948650487a3164d024e89670 to your computer and use it in GitHub Desktop.
Just some personal notes regarding http routing in golang
package main
import (
"fmt"
"io"
"log"
"net/http"
router "github.com/julienschmidt/httprouter"
)
func httprouter() {
handler := router.New()
handler.GET("/", func(writer http.ResponseWriter, request *http.Request, _ router.Params) {
io.WriteString(writer, "BOOM")
})
// handler.GET("/*var", func(writer http.ResponseWriter, request *http.Request, _ router.Params) {
// io.WriteString(writer, "You lookin' for this?")
// })
handler.GET("/hi%20there", func(writer http.ResponseWriter, request *http.Request, _ router.Params) {
io.WriteString(writer, "Escaped")
})
log.Fatal(http.ListenAndServe(":8080", handler))
}
type muxHandler struct{}
func (muxHandler) ServeHTTP (writer http.ResponseWriter, request *http.Request) {
io.WriteString(writer, "Hi there")
fmt.Printf("%#v\n\n", *request)
fmt.Printf("%#v\n\n", *request.URL)
}
func servemux() {
mux := http.NewServeMux()
mux.Handle("/hi/there", muxHandler{})
http.ListenAndServe(":8000", mux)
}
func servemux_better() {
mux := http.NewServeMux()
handler := func(writer http.ResponseWriter, request *http.Request) {
io.WriteString(writer, "Hi there")
fmt.Printf("%#v\n\n", *request)
fmt.Printf("%#v\n\n", *request.URL)
}
// mux.Handle("/hi/there", handler) // ERROR: doesn't implement ServeHTTP
mux.Handle("/hi/there", http.HandlerFunc(handler)) // <-- works!
http.ListenAndServe(":8000", mux)
}
func servemux_best() {
mux := http.NewServeMux()
mux.HandleFunc("/hi/there", func(writer http.ResponseWriter, request *http.Request) {
io.WriteString(writer, "Hi there")
fmt.Printf("%#v\n\n", *request)
fmt.Printf("%#v\n\n", *request.URL)
})
http.ListenAndServe(":8000", mux)
}
func main() {
// httprouter()
// servemux()
// servemux_better()
// servemux_best()
http.ListenAndServe(":8000", muxHandler{}) // muxHandler{} is already an http.Handler, since it has ServeHTTP() method.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment