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", envvar_name) envvar_value, isSet := os.LookupEnv(envvar_name) if !isSet { Error.Println(fmt.Sprintf("%v is not set", 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.Println(fmt.Sprintf("received %v on %v", r.Method, path)) paths := emptyArray(strings.Split(path, "/")) Info.Println(fmt.Sprintf("paths %v", 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.Println(fmt.Sprintf("%v not allowed", r.Method)) Error.Println(fmt.Sprintf("will return %v", 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.Println(fmt.Sprintf("%v not allowed", r.Method)) Error.Println(fmt.Sprintf("will return %v", 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.Println(fmt.Sprintf("running SFU on port %v", port)) err := http.ListenAndServe(port, mux) if err != nil { Error.Println(fmt.Sprintf("%v port may not be available", port)) os.Exit(1) } }