This repository has been archived by the owner on Mar 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
97 lines (72 loc) · 1.81 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
package main
import (
"fmt"
"log"
"io/ioutil"
"time"
"net/http"
"encoding/json"
"strconv"
)
const HOST string = "localhost"
const PORT int64 = 8888
type request struct {
Body string `json:"body"`
}
type response struct {
Body string
}
func main() {
log.Printf("Starting API server on " + HOST + ":" + strconv.FormatInt(PORT, 10))
http.HandleFunc("/", mainHandler)
http.HandleFunc("/test", testHandler)
err := http.ListenAndServe(HOST + ":" + strconv.FormatInt(PORT, 10), nil)
if err != nil {
log.Fatalf("Server failed to start. Error: %v", err)
}
}
/*
* Main response handler
*/
func mainHandler(w http.ResponseWriter, r *http.Request) {
st := time.Now()
log.Printf("Elapsed time: %v", time.Since(st))
w.Header().Set("Content-Type", "text/plain; charset=UTF-8")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "%s", string("API works. Send your POST test JSON to endpoint " +
HOST + ":" + strconv.FormatInt(PORT, 10) + "/test"))
}
/*
* Test handler
*/
func testHandler(w http.ResponseWriter, r *http.Request) {
st := time.Now()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
showErr(err, w)
return
}
jsonRequest := request{}
if json.Unmarshal(body, &jsonRequest) != nil {
showErr(err, w)
return
}
resp := response{Body: jsonRequest.Body}
jsonResp, err := json.Marshal(resp)
if err != nil {
showErr(err, w)
return
}
log.Printf("Served in %v", time.Since(st))
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "%s", string(`{"your_input": ` + string(jsonResp) + `}`))
}
/*
* Show an error to user
*/
func showErr(err error, w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"status": "error", "message": "%v"}`, err)
}