package main import ( "fmt" "net/http" "os" "regexp" "strings" ) var SFU_FILES_DIR string = getEnvvar("SFU_FILES_DIR") var SFU_PORT string = getEnvvar("SFU_PORT") func getEnvvar(envvar_name string) string { Info.Printf("getting envvar %v\n", envvar_name) envvar_value, isSet := os.LookupEnv(envvar_name) if !isSet { Error.Printf("%v is not set\n", envvar_name) os.Exit(1) } return envvar_value } func emptyArray(s []string) []string { var r []string for _, str := range s { if str != "" { r = append(r, str) } } return r } func routeFiles(w http.ResponseWriter, r *http.Request) { path := r.URL.Path Info.Printf("received %v on %v", r.Method, path) paths := emptyArray(strings.Split(path, "/")) Info.Printf("paths %v\n", paths) switch len(paths) { case 1: switch r.Method { case http.MethodGet: listFiles(w, r) case http.MethodPost: uploadFile(w, r) default: http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) Warning.Printf("%v not allowed\n", r.Method) Error.Printf("will return %v\n", http.StatusMethodNotAllowed) } return case 2: switch r.Method { case http.MethodGet: downloadFile(w, r, paths[1]) case http.MethodDelete: deleteFile(w, r, paths[1]) default: http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) Warning.Printf("%v not allowed\n", r.Method) Error.Printf("will return %v\n", http.StatusMethodNotAllowed) } default: http.Error(w, "Not found", http.StatusNotFound) } } func route(w http.ResponseWriter, r *http.Request) { path := r.URL.Path switch { case path == "/": fmt.Fprintf(w, "Hello, world!") case path == "/health": Info.Println("health check OK") w.WriteHeader(http.StatusOK) w.Write([]byte("OK")) case regexp.MustCompile("^/files").MatchString(path): Info.Println("received request for files, will call files router") routeFiles(w, r) default: w.WriteHeader(http.StatusNotFound) } } func main() { mux := http.NewServeMux() mux.HandleFunc("/", route) port := fmt.Sprintf(":%v", SFU_PORT) Info.Printf("running SFU on port %v\n", port) err := http.ListenAndServe(port, mux) if err != nil { Error.Printf("%v port may not be available\n", port) os.Exit(1) } }