-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
100 lines (79 loc) · 2.05 KB
/
main.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
package main
import (
"flag"
"io"
"log"
"net/http"
"os"
"path/filepath"
)
var (
flagDataPath string
flagCertFile string
flagKeyFile string
flagListenAddress string
)
func init() {
flag.StringVar(&flagCertFile, "certfile", "", "path to the certs file for https")
flag.StringVar(&flagKeyFile, "keyfile", "", "path to the keyfile for https")
flag.StringVar(&flagDataPath, "data_path", os.TempDir(), "path to the data storage directory")
flag.StringVar(&flagListenAddress, "listen_address", "0.0.0.0:8080", "address:port to bind listener on")
}
func main() {
if !flag.Parsed() {
flag.Parse()
}
router := http.NewServeMux()
router.HandleFunc("/", requestHandler)
if flagCertFile != "" && flagKeyFile != "" {
http.ListenAndServeTLS(flagListenAddress, flagCertFile, flagKeyFile, router)
} else {
http.ListenAndServe(flagListenAddress, router)
}
}
func requestHandler(res http.ResponseWriter, req *http.Request) {
if req.URL.Path == "/" {
http.NotFound(res, req)
return
}
stateStorageFile := filepath.Join(flagDataPath, req.URL.Path)
stateStorageDir := filepath.Dir(stateStorageFile)
switch req.Method {
case "GET":
fh, err := os.Open(stateStorageFile)
if err != nil {
log.Printf("cannot open file: %s\n", err)
goto not_found
}
defer fh.Close()
res.WriteHeader(200)
io.Copy(res, fh)
return
case "POST":
if err := os.MkdirAll(stateStorageDir, 0750); err != nil && !os.IsExist(err) {
log.Printf("cannot create parent directories: %s\n", err)
goto not_found
}
fh, err := os.OpenFile(stateStorageFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
log.Printf("cannot open file: %s\n", err)
goto not_found
}
defer fh.Close()
if _, err := io.Copy(fh, req.Body); err != nil {
log.Printf("failed to stream data into statefile: %s\n", err)
goto not_found
}
res.WriteHeader(200)
return
case "DELETE":
if os.RemoveAll(stateStorageFile) != nil {
log.Printf("cannot remove file: %s\n", err)
goto not_found
}
res.WriteHeader(200)
return
}
not_found:
http.NotFound(res, req)
}