/
http.go
68 lines (59 loc) · 1.26 KB
/
http.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
package main
import (
"io/ioutil"
"net/http"
"strings"
"github.com/ancientlore/hashsrv/engine"
)
const (
prefix = "hashsrv-"
prefixLen = len(prefix)
)
func root(w http.ResponseWriter, r *http.Request) {
// read body
b, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Initialize engine and initial value
eng := engine.New()
if r.Method == "POST" || r.Method == "PUT" {
eng.PushStack(b)
}
// initialize variables map
eng.SetVariable("body", b)
for k, v := range r.Header {
if strings.HasPrefix(strings.ToLower(k), prefix) && len(v) > 0 {
eng.SetVariable(k[prefixLen:], []byte(v[0]))
}
}
// check for debug mode
if r.URL.Query().Get("debug") != "" {
eng.DebugMode = true
}
// process commands
p := strings.TrimPrefix(r.URL.Path, "/")
var arr []string
if p != "" {
arr = strings.Split(p, "/")
} else {
arr = make([]string, 0)
}
var rb []byte
if len(arr) == 0 && r.Method == "GET" {
rb = eng.Help()
} else {
rb, err = eng.Run(arr)
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Write response
_, err = w.Write(rb)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}