-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient_http.go
87 lines (68 loc) · 1.89 KB
/
client_http.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
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"github.com/gin-gonic/gin"
)
type CalculateRequest struct {
Num1 float32 `json:"num1"`
Num2 float32 `json:"num2"`
Operation string `json:"operation"`
}
type CompareRequest struct {
Num1 float32 `json:"num1"`
Num2 float32 `json:"num2"`
}
func main() {
r := gin.Default()
baseURL := "http://localhost:8000"
// 路由1:计算操作
r.POST("/calculate", func(ctx *gin.Context) {
var req CalculateRequest
if err := ctx.BindJSON(&req); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
jsonData, err := json.Marshal(req)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
resp, err := http.Post(baseURL+"/calculate", "application/json", bytes.NewBuffer(jsonData))
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
ctx.JSON(http.StatusOK, result)
})
// 路由2:比较两个参数的大小并返回较大值
r.POST("/compare", func(ctx *gin.Context) {
var req CompareRequest
if err := ctx.BindJSON(&req); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
jsonData, err := json.Marshal(req)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
resp, err := http.Post(baseURL+"/compare", "application/json", bytes.NewBuffer(jsonData))
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
ctx.JSON(http.StatusOK, result)
})
r.Run(":8080")
}