-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
61 lines (46 loc) · 984 Bytes
/
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
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
)
type Request struct {
Name string `json:"name"`
}
type Response struct {
Message string `json:"message"`
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
message := "Hello world!"
ct := r.Header.Get("Content-Type")
if ct == "application/json" {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(500)
return
}
var req Request
if err := json.Unmarshal(b, &req); err != nil {
w.WriteHeader(500)
w.Write([]byte(err.Error()))
return
}
if len(req.Name) > 0 {
message = "Hello " + req.Name + "!"
}
if err := json.NewEncoder(w).Encode(Response{Message: message}); err != nil {
w.WriteHeader(500)
return
}
return
}
r.ParseForm()
name := r.Form.Get("name")
if len(name) > 0 {
message = "Hello " + name + "!"
}
w.Write([]byte(message))
})
http.ListenAndServe(":8080", nil)
}