|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "flag" |
| 5 | + "fmt" |
| 6 | + "io/ioutil" |
| 7 | + "log" |
| 8 | + "net/http" |
| 9 | + "os" |
| 10 | + "path" |
| 11 | + "strings" |
| 12 | + |
| 13 | + "github.com/gomarkdown/markdown" |
| 14 | +) |
| 15 | + |
| 16 | +var ( |
| 17 | + cwd, _ = os.Getwd() |
| 18 | + webRoot = flag.String("web-root", cwd, "Root of the web file tree.") |
| 19 | + host = flag.String("host", "127.0.0.1", "By default, the server is only accessible via localhost. "+ |
| 20 | + "Set to 0.0.0.0 or empty string to open to all.") |
| 21 | + port = flag.String("port", getEnvWithDefault("PORT", "8080"), "Port to listen on; $PORT env var overrides default value.") |
| 22 | +) |
| 23 | + |
| 24 | +func getEnvWithDefault(varName, defaultValue string) string { |
| 25 | + if value := os.Getenv(varName); value != "" { |
| 26 | + return value |
| 27 | + } |
| 28 | + return defaultValue |
| 29 | +} |
| 30 | + |
| 31 | +func stringHasOneOfSuffixes(str string, suffixes []string) bool { |
| 32 | + for _, suffix := range suffixes { |
| 33 | + if strings.HasSuffix(str, suffix) { |
| 34 | + return true |
| 35 | + } |
| 36 | + } |
| 37 | + return false |
| 38 | +} |
| 39 | + |
| 40 | +type DocHandler struct { |
| 41 | + webRoot string |
| 42 | +} |
| 43 | + |
| 44 | +func serveFile(rw http.ResponseWriter, mimeType string, fileContents []byte) { |
| 45 | + rw.WriteHeader(http.StatusOK) |
| 46 | + rw.Header().Set("Content-Type", fmt.Sprintf("%s; charset=UTF-8", mimeType)) |
| 47 | + rw.Write([]byte(fileContents)) |
| 48 | +} |
| 49 | + |
| 50 | +func (handler *DocHandler) DispatchHandler(rw http.ResponseWriter, req *http.Request) { |
| 51 | + log.Printf("Request: %s", req.URL.Path) |
| 52 | + var urlPath string = req.URL.Path |
| 53 | + // Remove any occurrences of `..` in the path to avoid escaping the web root. |
| 54 | + urlPath = strings.ReplaceAll(urlPath, "..", "") |
| 55 | + // Replace all multi-sequences of `/` with a single slash. |
| 56 | + urlPath = strings.ReplaceAll(urlPath, "//", "/") |
| 57 | + var fsPath string = path.Join(handler.webRoot, "/./", urlPath) |
| 58 | + |
| 59 | + log.Printf("Local path: %s", fsPath) |
| 60 | + |
| 61 | + fileInfo, err := os.Stat(fsPath) |
| 62 | + if err != nil && os.IsNotExist(err) { |
| 63 | + // File does not exist. |
| 64 | + rw.WriteHeader(http.StatusNotFound) |
| 65 | + rw.Header().Set("Content-Type", "text/html; charset=UTF-8") |
| 66 | + rw.Write([]byte("<!DOCTYPE html>\n")) |
| 67 | + rw.Write([]byte("<html>")) |
| 68 | + rw.Write([]byte("<body>")) |
| 69 | + rw.Write([]byte(fmt.Sprintf("<h1>Error 404: <code>%s</code> not found", urlPath))) |
| 70 | + rw.Write([]byte("</body>")) |
| 71 | + rw.Write([]byte("</html>")) |
| 72 | + |
| 73 | + log.Printf("Path not found: %s", fsPath) |
| 74 | + return |
| 75 | + } |
| 76 | + |
| 77 | + if fileInfo.IsDir() { |
| 78 | + files, err := ioutil.ReadDir(fsPath) |
| 79 | + if err != nil { |
| 80 | + log.Printf("Error listing directory: %s", fsPath) |
| 81 | + return |
| 82 | + } |
| 83 | + |
| 84 | + rw.WriteHeader(http.StatusOK) |
| 85 | + rw.Header().Set("Content-Type", "text/html; charset=UTF-8") |
| 86 | + rw.Write([]byte("<!DOCTYPE html>\n")) |
| 87 | + rw.Write([]byte("<html>")) |
| 88 | + rw.Write([]byte("<body>")) |
| 89 | + rw.Write([]byte(fmt.Sprintf("<h1>Directory listing: %s</h1>", urlPath))) |
| 90 | + rw.Write([]byte("<ul>")) |
| 91 | + for _, file := range files { |
| 92 | + // Skip internal files, e.g., `.git` directory, `.gitignore`, other dotfiles, etc. |
| 93 | + if strings.HasPrefix(file.Name(), ".") { |
| 94 | + continue |
| 95 | + } |
| 96 | + var listItem string |
| 97 | + if urlPath == "/" { |
| 98 | + listItem = fmt.Sprintf("<li><a href='%s'>%s</li>\n", file.Name(), file.Name()) |
| 99 | + } else { |
| 100 | + listItem = fmt.Sprintf("<li><a href='%s/%s'>%s</li>\n", urlPath, file.Name(), file.Name()) |
| 101 | + } |
| 102 | + rw.Write([]byte(listItem)) |
| 103 | + } |
| 104 | + rw.Write([]byte("</ul>")) |
| 105 | + rw.Write([]byte("</body>")) |
| 106 | + rw.Write([]byte("</html>")) |
| 107 | + return |
| 108 | + } |
| 109 | + |
| 110 | + fileContents, err := ioutil.ReadFile(fsPath) |
| 111 | + if err != nil { |
| 112 | + log.Printf("Error reading file (%s): %s", fsPath, err) |
| 113 | + return |
| 114 | + } |
| 115 | + |
| 116 | + if strings.HasSuffix(fsPath, ".html") { |
| 117 | + serveFile(rw, "text/html", fileContents) |
| 118 | + } else if strings.HasSuffix(fsPath, ".js") { |
| 119 | + serveFile(rw, "text/javascript", fileContents) |
| 120 | + } else if strings.HasSuffix(fsPath, ".ts") { |
| 121 | + serveFile(rw, "text/typescript", fileContents) |
| 122 | + } else if strings.HasSuffix(fsPath, ".css") { |
| 123 | + serveFile(rw, "text/css", fileContents) |
| 124 | + } else if strings.HasSuffix(fsPath, ".md") { |
| 125 | + rw.WriteHeader(http.StatusOK) |
| 126 | + rw.Header().Set("Content-Type", "text/html; charset=UTF-8") |
| 127 | + rw.Write([]byte(`<!doctype html> |
| 128 | +<html> |
| 129 | +<head> |
| 130 | + <style> |
| 131 | + code { |
| 132 | + background-color: #efefef; |
| 133 | + margin: 3px; |
| 134 | + padding: 3px; |
| 135 | + } |
| 136 | + </style> |
| 137 | +</head> |
| 138 | +<body>`)) |
| 139 | + rw.Write(markdown.ToHTML(fileContents, nil, nil)) |
| 140 | + rw.Write([]byte(`</body> |
| 141 | +</html>`)) |
| 142 | + } else if stringHasOneOfSuffixes(fsPath, []string{".txt", ".text", ".json", ".sh"}) { |
| 143 | + rw.Header().Set("Content-Type", "text/plain; charset=UTF-8") |
| 144 | + rw.Write(fileContents) |
| 145 | + } else { |
| 146 | + rw.Header().Set("Content-Type", "text/plain; charset=UTF-8") |
| 147 | + rw.Write([]byte("Unrecognized file content type or suffix.")) |
| 148 | + log.Printf("Unrecognized file content type or suffix: %s", fsPath) |
| 149 | + } |
| 150 | +} |
| 151 | + |
| 152 | +func NewDocHandler(webRoot string) *DocHandler { |
| 153 | + return &DocHandler{webRoot: webRoot} |
| 154 | +} |
| 155 | + |
| 156 | +func main() { |
| 157 | + flag.Parse() |
| 158 | + |
| 159 | + handler := NewDocHandler(*webRoot) |
| 160 | + http.HandleFunc("/", handler.DispatchHandler) |
| 161 | + |
| 162 | + hostPort := fmt.Sprintf("%s:%s", *host, *port) |
| 163 | + log.Printf("Listening on http://%s", hostPort) |
| 164 | + log.Printf("Serving from %s", *webRoot) |
| 165 | + log.Fatal(http.ListenAndServe(hostPort, nil)) |
| 166 | +} |
0 commit comments