You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 lines
1.7 KiB

2 years ago
package main
import (
"fmt"
"net"
"net/rpc"
"net/rpc/jsonrpc"
)
/*
@Auth:ShenZ
@Description:
*/
type User struct {
Name, Pwd string
Age, Score int
}
// 1.2个参数都是可序列化 参数1表示的是请求 参数2 响应 指针类型
// 2.方法必须公开的
// 3.返回 error类型
func (user *User) GetScore(u User, resp *int) error {
*resp = u.Age * u.Score
return nil
}
type Goods struct {
}
// 请求的结构体
type AddGoodsReq struct {
Name string
}
type AddGoodsResp struct {
Success bool
Message string
}
func (g Goods) AddGoods(req AddGoodsReq, resp *AddGoodsResp) error {
fmt.Println(req.Name, " GORM 入库操作 ")
*resp = AddGoodsResp{
Success: true,
Message: "新增商品成功!",
}
return nil
}
type QueryGoodsReq struct {
Id int
Name string
}
type QueryGoodsResp struct {
Success bool
Goods Goods
Message string
}
func (g Goods) QueryGoods(req QueryGoodsReq, resp *QueryGoodsResp) error {
fmt.Println(req.Name, " GORM 查询成功 ")
*resp = QueryGoodsResp{
Success: true,
Goods: Goods{},
Message: "查询成功!",
}
return nil
}
func main() {
//user := new(User)
goods := new(Goods)
//1.注册服务
//rpc.Register(goods)
rpc.RegisterName("goods", goods)
//2.绑定到http
rpc.HandleHTTP()
//3.加入监听
//err := http.ListenAndServe(":8081", nil)
listen, err := net.Listen("tcp", "127.0.0.1:8081")
if err != nil {
fmt.Println("服务启动失败", err)
}
defer listen.Close()
for {
//接收到的连接
conn, err1 := listen.Accept()
if err1 != nil {
fmt.Println("处理请求失败", err1)
}
rpc.ServeConn(conn)
//指定编码
rpc.ServeCodec(jsonrpc.NewServerCodec(conn))
}
}