-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathr3x.go
87 lines (65 loc) · 1.62 KB
/
r3x.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
package r3x
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
)
func Execute (r3xFunc func(map[string]interface{}) []byte) {
HTTPStream(r3xFunc)
}
func HTTPStream(r3xFunc func(map[string]interface{}) []byte){
port := os.Getenv("PORT")
if port == "" {
log.Fatal("PORT environment variable was not set")
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){
if r.Method != "POST" {
errorHandler(w, "Invalid Request", http.StatusInternalServerError)
return
}
m := jsonHandler(w, r)
b := r3xFunc(m)
var f interface{}
err := json.Unmarshal(b, &f)
if err != nil {
errorHandler(w, err.Error(), http.StatusInternalServerError)
return
}
js, err := json.MarshalIndent(&f, "", "\t")
if err != nil {
errorHandler(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(js)
})
err := http.ListenAndServe(":"+port, nil)
if err != nil {
log.Fatal("Could not listen: ", err)
}
}
func jsonHandler(w http.ResponseWriter, r *http.Request) map[string]interface{} {
body, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
errorHandler(w, err.Error(), http.StatusInternalServerError)
}
var m map[string]interface{}
if len(body) > 0 {
var bf interface{}
err = json.Unmarshal(body, &bf)
if err != nil {
errorHandler(w, err.Error(), http.StatusInternalServerError)
}
m = bf.(map[string]interface{})
}
return m
}
func errorHandler(w http.ResponseWriter, error string, num int){
fmt.Println("Error : " , error)
http.Error(w,error, num)
}