-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
82 lines (68 loc) · 1.98 KB
/
server.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
/*
Serve is a very simple static file server in go
Usage:
-p="8100": port to serve on
-d=".": the directory of static files to host
Navigating to http://localhost:8100 will display the index.html or directory
listing file.
*/
package main
import (
"flag"
auth "github.com/abbot/go-http-auth"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
)
var port = flag.String("p", "8100", "port to serve on")
var directory = flag.String("d", ".", "the directory of files to host")
func main() {
flag.Parse()
fs := http.FileServer(http.Dir(*directory))
http.Handle("/files/", http.StripPrefix("/files/", fs))
ss := http.FileServer(http.Dir("statics"))
http.Handle("/statics/", http.StripPrefix("/statics/", ss))
htppasswd := os.Getenv("HTPASSWD_FILE")
if htppasswd == "" {
http.HandleFunc("/", serveTemplate)
} else {
log.Printf("Using '%s' http basic auth file\n", htppasswd)
h := auth.HtpasswdFileProvider(htppasswd)
a := auth.NewBasicAuthenticator("File-qrs Realm", h)
http.Handle("/", a.Wrap(serveAuthTemplate))
}
log.Printf("Serving %s on HTTP port: %s\n", *directory, *port)
log.Fatal(http.ListenAndServe(":"+*port, nil))
}
func serveAuthTemplate(w http.ResponseWriter, ar *auth.AuthenticatedRequest) {
serveTemplate(w, &ar.Request)
}
func serveTemplate(w http.ResponseWriter, r *http.Request) {
var template_name string
if template_name = filepath.Clean(r.URL.Path); template_name == "/" {
template_name = "/index.html"
}
lp := filepath.Join("templates", "layout.html")
fp := filepath.Join("templates", template_name)
files, err := IOReadDir(*directory)
if err != nil {
log.Fatal(err)
}
log.Printf("Template %s\n", template_name)
tmpl, _ := template.ParseFiles(lp, fp)
tmpl.ExecuteTemplate(w, "layout", files)
}
func IOReadDir(root string) ([]string, error) {
var files []string
fileInfo, err := ioutil.ReadDir(root)
if err != nil {
return files, err
}
for _, file := range fileInfo {
files = append(files, file.Name())
}
return files, nil
}