-
Notifications
You must be signed in to change notification settings - Fork 8
/
server.go
65 lines (54 loc) · 1.17 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
// Copyright 2020 Hajime Hoshi
// SPDX-License-Identifier: Apache-2.0
//go:build ignore
package main
import (
"flag"
"log"
"net/http"
"os"
"path/filepath"
)
var (
httpAddr = flag.String("http", ":8000", "HTTP address")
)
var rootPath = ""
func init() {
flag.Parse()
dir := flag.Arg(0)
if dir == "" {
dir = "."
}
rootPath = dir
}
type handler struct{}
func (handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
path := filepath.Join(rootPath, r.URL.Path[1:])
f, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
w.WriteHeader(http.StatusNotFound)
http.ServeFile(w, r, filepath.Join(rootPath, "404.html"))
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if f.IsDir() {
path = filepath.Join(path, "index.html")
if _, err := os.Stat(path); err != nil {
if os.IsNotExist(err) {
w.WriteHeader(http.StatusNotFound)
http.ServeFile(w, r, filepath.Join(rootPath, "404.html"))
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
http.ServeFile(w, r, path)
}
func main() {
http.Handle("/", handler{})
log.Fatal(http.ListenAndServe(*httpAddr, nil))
}