-
Notifications
You must be signed in to change notification settings - Fork 18
/
hapttic.go
145 lines (119 loc) · 3.76 KB
/
hapttic.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
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"unicode/utf8"
)
const version = "1.0.0"
// This is a subset of http.Request with the types changed so that we can marshall it.
type marshallableRequest struct {
Method string
URL string
Proto string
Host string
Header http.Header
ContentLength int64
Body string
Form url.Values
PostForm url.Values
}
func init() {
log.SetOutput(os.Stdout)
}
func ensureRequestHandlingScriptExists(scriptFileName string) {
if _, err := os.Stat(scriptFileName); os.IsNotExist(err) {
log.Fatal("The request handling script " + scriptFileName + " does not exist.")
}
}
// handleFuncWithScriptFileName constructs our handleFunc
func handleFuncWithScriptFileName(scriptFileName string, logErrorsToStderr bool) func(s http.ResponseWriter, req *http.Request) {
return func(res http.ResponseWriter, req *http.Request) {
ensureRequestHandlingScriptExists(scriptFileName)
// This parses the request body
bodyBuffer := new(bytes.Buffer)
bodyBuffer.ReadFrom(req.Body)
body := bodyBuffer.String()
req.ParseForm()
// Copy over all the information from the request we are interested in
marshallableReq := marshallableRequest{
Method: req.Method,
URL: req.URL.String(),
Proto: req.Proto,
Host: req.Host,
Header: req.Header,
ContentLength: req.ContentLength,
Body: body,
Form: req.Form,
PostForm: req.PostForm,
}
// Try to convert to JSON. This shouldn't fail
requestJSON, err := json.Marshal(marshallableReq)
if err != nil {
log.Fatal(err)
}
log.Println("Executing " + scriptFileName)
// Execute the request handling script
out, err := exec.Command("/bin/bash", scriptFileName, string(requestJSON)).Output()
if err != nil {
// If there was an error, we return a response with status code 500
res.WriteHeader(http.StatusInternalServerError)
io.WriteString(res, "500 Internal Server Error")
if logErrorsToStderr {
log.Println("\033[33;31m--- ERROR: ---\033[0m")
log.Println("\033[33;31mParams:\033[0m")
log.Println(string(requestJSON))
log.Println("\033[33;31mScript output:\033[0m")
log.Println(string(out))
log.Println("\033[33;31m---- END: ----\033[0m")
}
} else {
// Otherwise we return the output of our script
res.Write(out)
}
}
}
func main() {
// Parse command line args
printVersion := flag.Bool("version", false, "Print version and exit.")
printUsage := flag.Bool("help", false, "Print usage and exit")
host := flag.String("host", "", "The host to bind to, e.g. 0.0.0.0 or localhost.")
port := flag.String("port", "8080", "The port to listen on.")
userScriptFileName := flag.String("file", "./hapttic_request_handler.sh", "The script that is called to handle requests.")
logErrorsToStderr := flag.Bool("logErrors", false, "Log errors to stderr")
flag.Parse()
if *printVersion {
fmt.Fprintf(os.Stderr, version+"\n")
os.Exit(0)
}
if *printUsage {
fmt.Fprintf(os.Stderr, "Usage of hapttic:\n")
flag.PrintDefaults()
os.Exit(0)
}
if utf8.RuneCountInString(*userScriptFileName) == 0 {
log.Fatal("The path to the request handling script can not be empty.")
}
scriptFileName, err := filepath.Abs(*userScriptFileName)
if err != nil {
log.Fatal(err)
}
ensureRequestHandlingScriptExists(scriptFileName)
http.HandleFunc("/", handleFuncWithScriptFileName(scriptFileName, *logErrorsToStderr))
addr := *host + ":" + *port
log.Println("Thanks for using hapttic v" + version)
log.Println(fmt.Sprintf("Listening on %s", addr))
log.Println(fmt.Sprintf("Forwarding requests to %s", scriptFileName))
if *logErrorsToStderr {
log.Println("Logging errors to stderr")
}
log.Fatal(http.ListenAndServe(addr, nil))
}