-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Expand file tree
/
Copy pathhandler.go
More file actions
85 lines (72 loc) · 2.14 KB
/
Copy pathhandler.go
File metadata and controls
85 lines (72 loc) · 2.14 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package swagger
import (
"io"
"net/http"
"path/filepath"
"strings"
"time"
"github.com/rakyll/statik/fs"
)
// Handler returns an HTTP handler for Swagger UI
func Handler() http.Handler {
return &swaggerHandler{}
}
type swaggerHandler struct{}
func (h *swaggerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Set CORS headers
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type")
if r.Method == http.MethodOptions {
return
}
// Get the static file system
statikFS, err := fs.New()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Process the path
urlPath := strings.TrimPrefix(r.URL.Path, "/swagger")
if urlPath == "" || urlPath == "/" {
urlPath = "/index.html"
}
// Open the file
file, err := statikFS.Open(urlPath)
if err != nil {
http.Error(w, "File not found", http.StatusNotFound)
return
}
defer file.Close()
// Set the content-type
ext := filepath.Ext(urlPath)
if ct := getContentType(ext); ct != "" {
w.Header().Set("Content-Type", ct)
}
// Set caching headers
w.Header().Set("Cache-Control", "public, max-age=31536000")
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
// Serve the file
http.ServeContent(w, r, urlPath, time.Now(), file.(io.ReadSeeker))
}
// getContentType returns the content-type for a file extension
func getContentType(ext string) string {
switch strings.ToLower(ext) {
case ".html":
return "text/html"
case ".css":
return "text/css"
case ".js":
return "application/javascript"
case ".json":
return "application/json"
case ".png":
return "image/png"
case ".jpg", ".jpeg":
return "image/jpeg"
case ".svg":
return "image/svg+xml"
default:
return ""
}
}