-
Notifications
You must be signed in to change notification settings - Fork 2
/
util.go
47 lines (42 loc) · 1.09 KB
/
util.go
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
package main
import (
"net/http"
"net/url"
"os"
"github.com/shurcooL/httpgzip"
)
// copyRequestAndURL returns a copy of req and its URL field.
func copyRequestAndURL(req *http.Request) *http.Request {
r := *req
u := *req.URL
r.URL = &u
return &r
}
// stripPrefix returns request r with prefix of length prefixLen stripped from r.URL.Path.
// prefixLen must not be longer than len(r.URL.Path), otherwise stripPrefix panics.
// If r.URL.Path is empty after the prefix is stripped, the path is changed to "/".
func stripPrefix(r *http.Request, prefixLen int) *http.Request {
r2 := new(http.Request)
*r2 = *r
r2.URL = new(url.URL)
*r2.URL = *r.URL
r2.URL.Path = r.URL.Path[prefixLen:]
if r2.URL.Path == "" {
r2.URL.Path = "/"
}
return r2
}
// serveFile opens the file at path and serves it using httpgzip.ServeContent.
func serveFile(w http.ResponseWriter, req *http.Request, path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return err
}
httpgzip.ServeContent(w, req, fi.Name(), fi.ModTime(), f)
return nil
}