Skip to content

Instantly share code, notes, and snippets.

@gregghz
Created May 23, 2013 05:20
Show Gist options
  • Save gregghz/5632908 to your computer and use it in GitHub Desktop.
Save gregghz/5632908 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"log"
"net/http"
"reflect"
"strings"
)
type Handler struct {}
func (f *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// A special case for the index
path := r.URL.Path
if path == "/" {
path = "/index"
}
// we need to do some processing to turn the url into a callable name
// after a POST request to /user/login, call_name will be "User_login_POST"
call_name := strings.ToUpper(path[1:2]) // capitalize the first letter .. we can only call exported methods
call_name += strings.Replace(strings.ToLower(path[2:]), "/", "_", -1)
call_name += "_" + r.Method
method := reflect.ValueOf(f).MethodByName(call_name)
if method.IsValid() {
method.Call([]reflect.Value{reflect.ValueOf(w), reflect.ValueOf(r)})
} else {
// send off a 404 error here.
w.WriteHeader(http.StatusNotFound)
}
}
func (h *Handler) Index_GET(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Index")
}
func (h *Handler) Pagetwo_GET(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "GET Page Two!")
}
func (h *Handler) Pagetwo_POST(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "POST Page Two!")
}
func main() {
s := &http.Server{
Addr: ":2056",
Handler: new(Handler),
}
log.Fatal(s.ListenAndServe())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment