/
server.go
190 lines (169 loc) · 4.87 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
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
package main
import (
"encoding/json"
"errors"
"fmt"
flags "github.com/jessevdk/go-flags"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
)
type ResponseData struct {
StatusCode int `json:"-"`
Key string `json:"key"`
IsNamespace bool `json:"namespace"`
Value string `json:"value"`
Keys []string `json:"keys,omitempty"` // need better decision here
Error string `json:"error,omitempty"` // need better decision here
}
var validKey = regexp.MustCompile(`^[a-zA-Z0-9_\-/:]+$`)
func handler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
var responseData ResponseData
key := r.URL.Path[1:]
if validKey.MatchString(key) {
key_path := expandPath(key)
value := r.PostForm.Get("value")
var keys []string
var err error
switch r.Method {
case "GET":
var values []string
var isNamespace bool
values, isNamespace, err = readKey(key_path)
if err == nil {
if isNamespace {
keys = values
} else {
value = values[0]
}
}
case "DELETE":
err = deleteKey(key_path)
case "PUT", "POST":
err = putKey(key_path, value)
}
if err == nil {
responseData = ResponseData{StatusCode: http.StatusOK, Key: key, Value: value, Keys: keys}
if keys == nil {
responseData.IsNamespace = false
} else {
responseData.IsNamespace = true
}
} else {
responseData = ResponseData{StatusCode: http.StatusNotFound, Key: key, Error: err.Error()}
}
} else {
responseData = ResponseData{StatusCode: http.StatusBadRequest, Key: key, Error: "Invalid key. Only " + validKey.String() + " allowed!"}
}
content, err := json.Marshal(responseData)
if err == nil && responseData.StatusCode != 0 {
callHooks(key, r.Method)
w.WriteHeader(responseData.StatusCode)
w.Header().Set("Content-Type", "application/json")
w.Write(append(content, '\n'))
} else {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(http.StatusText(http.StatusInternalServerError)))
fmt.Println(err)
}
}
func readKey(path string) ([]string, bool, error) {
var result []string
var err error
var fileInfo os.FileInfo
fileInfo, err = os.Stat(path)
isNamespace := false
if err == nil {
if fileInfo.IsDir() {
isNamespace = true
var files []os.FileInfo
if files, err = ioutil.ReadDir(path); err == nil {
for _, f := range files {
result = append(result, f.Name())
}
}
} else {
var content []byte
if content, err = ioutil.ReadFile(path); err == nil {
result = append(result, string(content))
}
}
}
return result, isNamespace, err
}
func putKey(path string, value string) error {
os.MkdirAll(filepath.Dir(path), os.ModePerm)
return ioutil.WriteFile(path, []byte(value), os.ModePerm)
}
func deleteKey(path string) error {
return os.Remove(path)
}
func expandPath(key string) string {
return filepath.Join(opts.DataPath, key)
}
// Return nil if File exists, else non-nil value
func fileExists(filename string) error {
_, err := os.Stat(filename)
return err
}
// Return nil if filename is a directory, else non-nil value
func isDirectory(filename string) error {
stat, err := os.Stat(filename)
if err == nil && !stat.IsDir() {
return errors.New("'" + filename + "' is not a directory!")
}
return nil
}
func callHooks(key, action string) {
keyparts := strings.Split(key, "/")
tmpkey := keyparts[0]
callHook(tmpkey, action)
for _, keypart := range keyparts[1:] {
tmpkey = tmpkey + "/" + keypart
callHook(tmpkey, action)
}
}
// ignore errors, just print them and continue
func callHook(key, action string) {
for _, hookUrl := range opts.WebHookUrls {
go func(hookUrl string, hookData url.Values) {
if _, err := http.PostForm(hookUrl, hookData); err != nil {
fmt.Printf("WebHook Post failed: %s\n", err)
} else {
fmt.Printf("Called '%s' with Payload '%+v'.\n", hookUrl, hookData)
}
}(hookUrl, url.Values{"key": {key}, "action": {action}})
}
}
var opts struct {
DataPath string `short:"d" long:"data-path" default:"./data" description:"Directory where files will be stored."`
Port int `short:"p" long:"port" default:"8080" description:"Port where server is listening for requests."`
WebHookUrls []string `short:"w" long:"webhook-url" description:"WebHook-Urls."`
}
func main() {
flags.Parse(&opts)
opts.DataPath, _ = filepath.Abs(opts.DataPath)
fmt.Println("DATA_PATH:", opts.DataPath)
fmt.Println("PORT:", opts.Port)
for i, hookUrl := range opts.WebHookUrls {
if len(hookUrl) >= 4 && hookUrl[:4] != "http" {
opts.WebHookUrls[i] = "http://" + hookUrl
}
}
fmt.Printf("HOOKS: %+v\n", opts.WebHookUrls)
deviceMux := http.NewServeMux()
deviceMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
p := r.URL.Path
r.URL.Path = "/devices" + p
handler(w, r)
})
go http.ListenAndServe(":82", deviceMux)
http.HandleFunc("/", handler)
http.ListenAndServe(":"+strconv.Itoa(opts.Port), nil)
}