-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathnever-cache.go
More file actions
65 lines (59 loc) · 1.4 KB
/
never-cache.go
File metadata and controls
65 lines (59 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
import (
"flag"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
)
func maybeSetContentTypeFromPath(w http.ResponseWriter, path string) {
extensionMimeMap := map[string]string{
".css": "text/css",
".js": "text/javascript",
}
mimeType, ok := extensionMimeMap[filepath.Ext(path)]
if ok {
w.Header().Add("Content-Type", mimeType)
}
return
}
func checkPath(path string, root string) (string, error) {
if len(path) == 0 {
path = "index.html"
}
absPath, err := filepath.Abs(path)
if err != nil {
return "", err
}
if len(absPath) <= len(root) || absPath[0:len(root)] != root || !os.IsPathSeparator(absPath[len(root)]) {
return "", fmt.Errorf("\"%s\" is not within \"%s\"", path, root)
}
return absPath, nil
}
func handler(w http.ResponseWriter, r *http.Request) {
cwd, err := os.Getwd()
var path string
if err == nil {
path, err = checkPath(r.URL.Path[1:], cwd)
}
if err != nil {
log.Printf("Error: %s", err)
http.Error(w, "Not Found", 404)
return
}
log.Print(r.URL.Path)
w.Header().Add("Cache-Control", "private, max-age=0, no-cache")
http.ServeFile(w, r, path)
}
func main() {
var port int
flag.IntVar(&port, "port", 8080, "Serve files under the current directory on this port")
flag.Parse()
http.HandleFunc("/", handler)
log.Print("Starting...")
err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
if err != nil {
log.Fatal(err)
}
}