-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
143 lines (118 loc) · 3.22 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
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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"os"
"path"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
var fileToSend string = "data.json"
var endpoint string = "data"
var servicePort int = 3080
func initialize() error {
return nil
}
func main() {
start()
}
func start() {
log.Printf("Initialize")
err := initialize()
if err != nil {
log.Fatalf("Initialization failed, error: %s\n", err.Error())
}
serviceIP := "0.0.0.0"
serviceAddress := fmt.Sprintf("%v:%v", serviceIP, servicePort)
log.Printf("Starting service at: %v\n", serviceAddress)
log.Printf(" serving GET requests from endpoint: %s, sending: %s\n", path.Join("/", endpoint), fileToSend)
log.Printf(" serving POST requests to endpoint: %s\n", path.Join("/", endpoint))
r, err := NewHTTPApi()
if err != nil {
log.Panicln(err)
}
// Where ORIGIN_ALLOWED is like `scheme://dns[:port]`, or `*` (insecure)
err = http.ListenAndServe(serviceAddress, handlers.LoggingHandler(os.Stdout, r))
if err != nil {
log.Panicln(err)
}
}
//
// APIServer is the middle-ware interface
//
type APIServer struct {
Handler func(http.ResponseWriter, *http.Request) (int, error)
}
//
// NewHTTPApi constructor
//
func NewHTTPApi() (*mux.Router, error) {
r := mux.NewRouter()
serverEndpoint := path.Join("/", endpoint)
r.Handle(serverEndpoint, APIServer{getHandler}).Methods("GET")
r.Handle(serverEndpoint, APIServer{postHandler}).Methods("POST")
return r, nil
}
//
// ServeHTTP is just the wrapper which calls the handler for the API
//
func (ah APIServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ah.Handler(w, r)
}
func sendRawAsJSONResponse(w http.ResponseWriter, payload []byte) (int, error) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(payload))
return http.StatusOK, nil
}
func sendJSONResponse(w http.ResponseWriter, data interface{}) (int, error) {
payload, err := json.Marshal(data)
if err != nil {
return http.StatusInternalServerError, err
}
return sendRawAsJSONResponse(w, payload)
}
func getHandler(w http.ResponseWriter, r *http.Request) (int, error) {
// import data
data, err := ioutil.ReadFile(fileToSend)
if err != nil {
log.Fatalf("Unable to read file: %s\n", fileToSend)
return http.StatusInternalServerError, err
}
log.Printf("Sending:\n%s\n", data)
return sendRawAsJSONResponse(w, data)
}
func dumpMap(space string, m map[string]interface{}) {
for k, v := range m {
if mv, ok := v.(map[string]interface{}); ok {
fmt.Printf("{ \"%v\": \n", k)
dumpMap(space+"\t", mv)
fmt.Printf("}\n")
} else {
fmt.Printf("%v %v : %v\n", space, k, v)
}
}
}
func postHandler(w http.ResponseWriter, r *http.Request) (int, error) {
// import data
log.Printf("got request, dumping body\n")
data, err := httputil.DumpRequest(r, true)
if err != nil {
log.Printf("Error: %v\n", err)
return http.StatusInternalServerError, err
}
log.Printf("Body: \n%s\n", string(data))
log.Printf("Parsing JSON\n")
jsonMap := make(map[string]interface{})
err = json.NewDecoder(r.Body).Decode(&jsonMap)
if err != nil {
log.Printf("Failed to unmarshal: %v\n", err)
} else {
log.Printf("Ok, dumping JSON data\n")
dumpMap("", jsonMap)
}
return http.StatusOK, nil
}