blob: 3fad80080795b17012f75ed2c5ba3495093cecb7 [file] [log] [blame]
Philipp Schraderad2a6fb2024-03-20 20:51:36 -07001package main
2
3import (
4 "flag"
5 "fmt"
6 "log"
7 "net/http"
8)
9
10var authorized = false
11var authorizedCounter = 0
12
13// Special handler for responding to /submit requests.
14func handleSubmission(w http.ResponseWriter, r *http.Request) {
15 if !authorized {
16 log.Println("Replying with 'Unauthorized'.")
17 w.WriteHeader(http.StatusUnauthorized)
18 w.Write([]byte{})
19 return
20 }
21
22 log.Println("Replying with success.")
23 authorizedCounter += 1
24 w.Write([]byte(fmt.Sprintf("Successful submission %d!", authorizedCounter)))
25}
26
27// Default handler for all other requests.
28func createDefaultHandler(directory string) http.HandlerFunc {
29 handler := http.FileServer(http.Dir(directory))
30
31 fn := func(w http.ResponseWriter, r *http.Request) {
32 if r.URL.Path == "/authorize" {
33 authorized = true
34 }
35 handler.ServeHTTP(w, r)
36 }
37
38 return http.HandlerFunc(fn)
39}
40
41func main() {
42 directoryPtr := flag.String("directory", ".", "The directory to serve")
43 flag.Parse()
44
45 http.HandleFunc("/", createDefaultHandler(*directoryPtr))
46 http.HandleFunc("/submit", handleSubmission)
47
48 fmt.Println("Server listening on port 8000...")
49 http.ListenAndServe(":8000", nil)
50}