-
Notifications
You must be signed in to change notification settings - Fork 0
/
request_handler_post.go
83 lines (67 loc) · 1.55 KB
/
request_handler_post.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
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"fmt"
"log"
)
type resp_format struct {
Result int `json:"result"`
Success bool `json:"success"`
}
type req_params struct {
A int `json:"a"`
B int `json:"b"`
}
func main() {
http.HandleFunc("/add", add_params)
http.HandleFunc("/sub", sub_params)
http.ListenAndServe(":9988", nil)
}
func add_params(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Println(err)
}
var params req_params
err = json.Unmarshal(body, ¶ms)
if err != nil {
log.Println(err)
}
a := params.A
b := params.B
sum_val := a + b
val := resp_format{Result: sum_val, Success: true}
resp, err := json.Marshal(val)
if err != nil {
fmt.Println("error =", err)
return
}
log.Println(r)
w.Header().Set("Content-Type", "application/json; char-set: utf-8")
w.Write(resp)
}
func sub_params(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Println(err)
}
var params req_params
err = json.Unmarshal(body, ¶ms)
if err != nil {
log.Println(err)
}
a := params.A
b := params.B
sub_val := a - b
val := resp_format{Result: sub_val, Success: true}
resp, err := json.Marshal(val)
if err != nil {
fmt.Println("error =", err)
return
}
log.Println(r)
w.Header().Set("Content-Type", "application/json")
w.Write(resp)
}