Skip to content

Instantly share code, notes, and snippets.

@corehello
Created January 4, 2015 11:20
Show Gist options
  • Save corehello/62a3358465f9bff9a5f2 to your computer and use it in GitHub Desktop.
Save corehello/62a3358465f9bff9a5f2 to your computer and use it in GitHub Desktop.
go http server with regex match router
package main
import (
"net/http"
"fmt"
"html"
"regexp"
"log"
"os"
"time"
)
var layout = "Jan 2, 2006 at 3:04:01pm (MST)"
var logger = log.New(os.Stdout, time.Now().Format(layout)+" => ", log.Lshortfile)
var routers =map[string]func(http.ResponseWriter, *http.Request){
"^/?$": hellohandle,
"^/test/?$": testhandle,
"^/regexp/[[:digit:]]/(edit|save)": regexphandle,
}
// define some httphandler
func handlerouters(w http.ResponseWriter, r *http.Request){
logger.Printf("%q, %q, %q", r.RemoteAddr, r.Method, r.URL.Path)
err := false
for k,v := range routers {
matched, _ := regexp.MatchString(k,r.URL.Path)
if matched == true {
v(w,r)
err = true
}
}
if err == false {
http.NotFound(w,r)
}
}
func hellohandle(w http.ResponseWriter, r *http.Request){
fmt.Fprintf(w, "test, %q", html.EscapeString(r.URL.Path))
}
func testhandle(w http.ResponseWriter, r *http.Request){
fmt.Fprintf(w, "test, %q", html.EscapeString(r.URL.Path))
}
func regexphandle(w http.ResponseWriter, r *http.Request){
fmt.Fprintf(w, "regex, %q", html.EscapeString(r.URL.Path))
}
//define function to add router for http server
func addrouter(sm *http.ServeMux, pattern string, handfunc func(http.ResponseWriter, *http.Request)) {
sm.HandleFunc(pattern, handfunc)
}
func main() {
router := http.NewServeMux()
addrouter(router, "/", handlerouters)
server := &http.Server{
Addr: ":8000",
Handler: router,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
logger.Printf("starting http service on port 8000")
go server.ListenAndServe()
select {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment