Philipp Schrader | ad2a6fb | 2024-03-20 20:51:36 -0700 | [diff] [blame] | 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "flag" |
| 5 | "fmt" |
| 6 | "log" |
| 7 | "net/http" |
| 8 | ) |
| 9 | |
| 10 | var authorized = false |
| 11 | var authorizedCounter = 0 |
| 12 | |
| 13 | // Special handler for responding to /submit requests. |
| 14 | func 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. |
| 28 | func 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 | |
| 41 | func 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 | } |