From 72e86f736dca3b2da6f200d91a459c8faab3e288 Mon Sep 17 00:00:00 2001 From: Emile Date: Sun, 6 Oct 2019 23:52:09 +0200 Subject: basic setup --- src/http.go | 86 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 src/http.go (limited to 'src/http.go') diff --git a/src/http.go b/src/http.go new file mode 100644 index 0000000..a9b4240 --- /dev/null +++ b/src/http.go @@ -0,0 +1,86 @@ +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)) + } +} -- cgit 1.4.1