http模拟RPC-go

lkpalu Lv3

记录

服务端

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
package main

import (
"fmt"
"github.com/gin-gonic/gin"
"log"
"strconv"
)

type PrintInfo struct {
A string `json:"a"`
B string `json:"b"`
//PrintInfos string `json:"print_info"`
}

func RpcS() {
var Prints PrintInfo
r := gin.Default()
r.POST("/", func(c *gin.Context) {
c.ShouldBindJSON(&Prints)
d, _ := strconv.Atoi(Prints.A)
e, _ := strconv.Atoi(Prints.B)
f := d + e
log.Println(d, e)
c.JSON(200, gin.H{
//"c": strconv.Itoa(strconv.Atoi(Prints.a) + strconv.Atoi(Prints.b)),
"D": f,
})
})
fmt.Println("start")
r.Run(":8080")
}
func main() {
RpcS()

}

客户端

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
package main

import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
)

type msg struct {
//Message string `json:"message"`
D int `json:"d"`
}
type PrintInfo struct {
A string `json:"a"`
B string `json:"b"`
}

func main() {
Prints := PrintInfo{
//PrintInfos: "Hello World",
A: "1",
B: "2",
}
marshal, _ := json.Marshal(Prints)
//fmt.Println(marshal)
resp, err := http.Post("http://localhost:8080", "application/json", bytes.NewBuffer(marshal)) // 添加了http://前缀以确保URL格式正确
if err != nil {
log.Fatalf("无法获取响应: %v", err) // 使用log.Fatalf来处理错误并终止程序
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
log.Fatalf("服务器返回错误状态码: %d", resp.StatusCode)
}

var m msg
if err := json.NewDecoder(resp.Body).Decode(&m); err != nil {
log.Fatalf("无法解码响应体: %v", err)
}

fmt.Println(m.D)
}
  • 标题: http模拟RPC-go
  • 作者: lkpalu
  • 创建于 : 2024-11-06 20:52:53
  • 更新于 : 2024-11-07 16:52:25
  • 链接: https://redefine.ohevan.com/2024/11/06/http模拟RPC-go/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论
目录
http模拟RPC-go