- Serve the current directory
- Map some extra paths to
/index.html - Also proxy
/css/*to a seperate webservice
Usage:
PORT=8080 PROXY_URL="http://localhost:5455/27850" go run main.go
| package main | |
| import ( | |
| "io" | |
| "io/ioutil" | |
| "net/http" | |
| "os" | |
| "strings" | |
| ) | |
| var allowedPaths = []string{ | |
| "photo", | |
| "characteristics", | |
| "interests", | |
| "personality", | |
| "introduction", | |
| "verification", | |
| } | |
| func contains(needle string, haystack []string) bool { | |
| for i := 0; i < len(haystack); i++ { | |
| if haystack[i] == needle { | |
| return true | |
| } | |
| } | |
| return false | |
| } | |
| func serv(proxy string, port string) { | |
| http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) { | |
| path := req.URL.Path[1:] | |
| if contains(path, allowedPaths) { | |
| http.ServeFile(res, req, "index.html") | |
| } else { | |
| http.StripPrefix("/", http.FileServer(http.Dir(""))).ServeHTTP(res, req) | |
| } | |
| }) | |
| http.HandleFunc("/css/", func(res http.ResponseWriter, req *http.Request) { | |
| path := req.URL.Path[1:] | |
| get, err := http.Get(proxy + strings.Replace(path, "css", "", 1)) | |
| if err != nil { | |
| http.NotFound(res, req) | |
| return | |
| } | |
| defer get.Body.Close() | |
| content, _ := ioutil.ReadAll(get.Body) | |
| res.Header().Set("Content-Type", "text/css") | |
| io.WriteString(res, string(content)) | |
| }) | |
| http.ListenAndServe(":"+port, nil) | |
| } | |
| func main() { | |
| proxy := os.Getenv("PROXY_URL") | |
| if proxy == "" { | |
| panic("please specify PROXY_URL environment variable") | |
| } | |
| port := os.Getenv("PORT") | |
| if port == "" { | |
| port = "9000" | |
| } | |
| serv(proxy, port) | |
| } |