/
Lab2.go
52 lines (40 loc) · 986 Bytes
/
Lab2.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"httprouter"
"net/http"
)
var string1 string
// Req represents the structure of request
type Req struct {
Name string `json:"name"`
}
// Resp represents the structure of request
type Resp struct {
Greeting string `json:"greeting"`
}
// GreetUser creates a new user resource
func GreetUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
u := Resp{}
u2 := Req{}
json.NewDecoder(r.Body).Decode(&u2)
var buffer bytes.Buffer
buffer.WriteString("Hello, ")
buffer.WriteString(u2.Name)
buffer.WriteString("!")
u.Greeting = buffer.String()
// Marshal provided interface into JSON structure
uj, _ := json.Marshal(u)
// Write content-type, statuscode, payload
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(201)
fmt.Fprintf(w, "%s", uj)
}
func main() {
// Instantiate a new router
r := httprouter.New()
r.POST("/hello", GreetUser)
http.ListenAndServe("localhost:8080", r)
}