package main import ( "flag" "fmt" "io/ioutil" "net/http" "strings" "github.com/gorilla/mux" ) var ( port *int // port the http server listens on usernames []string // list of usernames ) func registerHTTPFlags() { port = flag.Int("port", 8081, "The port the http server should listen on") } func setupHTTPServer() http.Server { r := mux.NewRouter() r.HandleFunc("/", indexHandler) r.HandleFunc("/register", registerGetHandler).Methods("GET") r.HandleFunc("/register", registerPostHandler).Methods("POST") return http.Server{ Addr: fmt.Sprintf("0.0.0.0:%d", *port), Handler: r, } } // Host of the index file func indexHandler(w http.ResponseWriter, r *http.Request) { readFileToReponse(w, "/index.html") } // Read register page func registerGetHandler(w http.ResponseWriter, r *http.Request) { readFileToReponse(w, "/register.html") } // Process a registration func registerPostHandler(w http.ResponseWriter, r *http.Request) { r.ParseForm() username := r.Form.Get("username") // test if the username has already been chosen if !isUniq(username) { w.Write([]byte("Username has already been taken.")) return } // add the new username to the list of usernames usernames = append(usernames, username) // generate a new accesscode accesscode := newAccessCode() // redirect the user to the front page http.Redirect(w, r, "/", http.StatusTemporaryRedirect) } func isUniq(username string) bool { for _, user := range usernames { if username == user { return false } } return true } func readFileToReponse(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)) } }