-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathfileserver.go
148 lines (131 loc) · 3.49 KB
/
fileserver.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
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
package fileserver
import (
"fmt"
"log"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"sort"
"strings"
"text/template"
utils "github.com/prdpx7/go-fileserver/utils"
)
type customFileHandler struct {
root http.FileSystem
}
//CustomFileServer ...
func CustomFileServer(root http.FileSystem) http.Handler {
return &customFileHandler{root}
}
func (cf *customFileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
upath := r.URL.Path
if !strings.HasPrefix(upath, "/") {
upath = "/" + upath
r.URL.Path = upath
}
ServeFile(w, r, cf.root, path.Clean(upath), true, "")
}
// ServeFile ...
func ServeFile(w http.ResponseWriter, r *http.Request, fs http.FileSystem, name string, redirect bool, templateName string) {
f, err := fs.Open(name)
if err != nil {
msg, code := toHTTPError(err)
http.Error(w, msg, code)
return
}
defer f.Close()
d, err := f.Stat()
if err != nil {
msg, code := toHTTPError(err)
http.Error(w, msg, code)
return
}
if d.IsDir() {
ListDirectory(w, r, f, templateName)
return
}
http.ServeContent(w, r, d.Name(), d.ModTime(), f)
}
func toHTTPError(err error) (msg string, httpStatus int) {
if os.IsNotExist(err) {
return "404 page not found", http.StatusNotFound
}
if os.IsPermission(err) {
return "403 Forbidden", http.StatusForbidden
}
// Default:
return "500 Internal Server Error", http.StatusInternalServerError
}
//ListDirectory render directory content in templateName.html
func ListDirectory(w http.ResponseWriter, r *http.Request, f http.File, templateName string) {
RootDir, err := f.Stat()
if err != nil {
panic(err)
}
var dirContents DirectoryContent
dirContents.DirName = RootDir.Name()
dirContents.Files = make([]FileContent, 0)
dirs, err := f.Readdir(-1)
if err != nil {
log.Printf("http: error reading directory: %v", err)
http.Error(w, "Error reading directory", http.StatusInternalServerError)
return
}
sort.Slice(dirs, func(i, j int) bool { return dirs[i].Name() < dirs[j].Name() })
w.Header().Set("Content-Type", "text/html; charset=utf-8")
for _, d := range dirs {
name := d.Name()
fileExtension := "page"
if d.IsDir() {
name += "/"
fileExtension = "folder"
} else if len(filepath.Ext(name)) > 1 {
fileExtension = filepath.Ext(name)[1:]
}
url := url.URL{Path: name}
fileContent := FileContent{Name: name, Size: utils.GetHumanReadableSize(d), URL: url, Extension: fileExtension}
dirContents.Files = append(dirContents.Files, fileContent)
}
dirContents.IPAddr = r.Host
renderTemplate(w, templateName, dirContents)
}
//DirectoryContent to be used in rendering Index Page
type DirectoryContent struct {
DirName string
Files []FileContent
IPAddr string
}
//FileContent ...
type FileContent struct {
Name string
Size string
URL url.URL
Extension string
}
func renderTemplate(w http.ResponseWriter, tmpl string, data interface{}) {
var t *template.Template
var err error
// use default rendering html
if len(tmpl) == 0 {
t = template.New("index")
t, err = t.Parse(utils.DirListTemplateHTML)
} else {
templatePath, _ := filepath.Abs(tmpl + ".html")
fmt.Println("template path", templatePath)
t, err = template.ParseFiles(templatePath)
}
if err != nil {
fmt.Println("Error in parsing template ", err)
panic(err)
}
t.Execute(w, data)
}
//RequestLogger ...
func RequestLogger(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL)
handler.ServeHTTP(w, r)
})
}