package main import ( "flag" "fmt" "io/ioutil" "log" "net/http" "strings" "github.com/gorilla/mux" ) var ( port *int ) func registerHTTPFlags() { port = flag.Int("port", 8080, "The port for HTTP") } func setupHTTPServer() http.Server { r := mux.NewRouter() r.HandleFunc("/", indexHandler) r.HandleFunc("/create", createGetHandler).Methods("GET") r.HandleFunc("/create", createPostHandler).Methods("POST") r.HandleFunc("/view", viewGetHandler).Methods("GET") r.HandleFunc("/edit", editGetHandler).Methods("GET") r.HandleFunc("/edit", editPostHandler).Methods("POST") return http.Server{ Addr: fmt.Sprintf("0.0.0.0:%d", *port), Handler: r, } } // Host the index file func indexHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "%s", "Hello World!\n") } func createGetHandler(w http.ResponseWriter, r *http.Request) { log.Println("create GET") readFileToResponse(w, "/create.html") } func createPostHandler(w http.ResponseWriter, r *http.Request) { log.Println("create POST") } func viewGetHandler(w http.ResponseWriter, r *http.Request) { log.Println("ciew GET") readFileToResponse(w, "/view.html") } func editGetHandler(w http.ResponseWriter, r *http.Request) { log.Println("edit GET") readFileToResponse(w, "/edit.html") } func editPostHandler(w http.ResponseWriter, r *http.Request) { log.Println("edit POST") } // Helper function to host files off of "hosted/" directory func readFileToResponse(w http.ResponseWriter, path string) { requestedFile := strings.Replace(path, "..", "", -1) contents, readError := ioutil.ReadFile(fmt.Sprintf("hosted/%s", requestedFile)) if readError != nil { w.Write([]byte(fmt.Sprintf("unable to read %s", requestedFile))) } else { w.Write([]byte(contents)) } }