about summary refs log tree commit diff
path: root/src/http.go
blob: 1b5db1a290c79d196a0c823a459ed8e58536c882 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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
	// map usernames to their companion containers
	// the companion containers get assigned a random string used to identify itself
	companion map[string]string
)

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))
	}
}