package main import ( "flag" "fmt" "io/ioutil" "log" "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) { log.Println("redirecting to usernameTaken") usernameTakenGetHandler(w, r) return } // add the new username to the list of usernames usernames = append(usernames, username) // generate a new accesscode accesscode := newAccessCode() log.Printf("Generated a new AccessCode for user %s: %s", username, accesscode) // generate a new companion spawnCompanion(username, accesscode) // redirect the user to the front page http.Redirect(w, r, "/", http.StatusTemporaryRedirect) } func usernameTakenGetHandler(w http.ResponseWriter, r *http.Request) { log.Println("[usernameTaken]") readFileToReponse(w, "/usernameTaken.html") } 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)) } }