Go嵌入接口类型

以下代码中,构建简单的ipc进程间通讯模型,ipcServer中嵌入Server接口,则在实例化时需要指定一个实现其嵌入接口的实现类。若嵌入接口中的方法与ipcServer中的方法不同,则自动升级至ipcServer类型中,通过ipcServer.funcName()即可引用,详情请看:

https://blog.csdn.net/weixin_34268310/article/details/92645136


package ipc

import (
	"encoding/json"
	"fmt"
)

type Request struct {
	Method string `json:"method"`
	Params string `json:"Params"`
}

type Response struct {
	Code string `json:"code"`
	Body string `json:"body"`
}

type Server interface {
	Name() string
	Handle(method, params string) *Response
}

type IpcServer struct {
	Server
}

func NewIpcServer(server Server) *IpcServer {
	return &IpcServer{server}
}

func (server *IpcServer) Connect() chan string {
	session := make(chan string, 0)

	go func(c chan string) {
		for {
			request := <-c

			if request == "CLOSE" { //关闭连接
				break
			}

			var req Request
			err := json.Unmarshal([]byte(request), &req) //将json字符串解码到相应的数据结构

			if err != nil {
				fmt.Println("Invaild request format: ", request)
				return
			}

			resp := server.Handle(req.Method,req.Params)

			b,err := json.Marshal(resp) //将resp对象转化成json数据字符串

			c<-string(b)
		}
		fmt.Println("Session closed.")

	}(session)

	fmt.Println("A new session has been created successfully.")
	return session
}


package ipc

import "testing"

type EchoServer struct {
}

func (server *EchoServer) Handle(method, params string) *Response {
	return &Response{"OK", "ECHO" + method + "~" + params}
}

func (server *EchoServer) Name() string {
	return "EchoServer"
}

func TestIpc(t *testing.T) {
	server := NewIpcServer(&EchoServer{})   //<------实例化  其中EchoServer实现了Server接口

	client1 := NewIpcClient(server)
	client2 := NewIpcClient(server)

	resp1, _ := client1.Call("foo", "From Client1")
	resp2, _ := client2.Call("foo", "From Client2")

	if resp1.Body != "ECHO: foo ~ From Client1" || resp2.Body != "ECHO: foo ~ From Client2" {
		t.Error("IpcClient.Call failed. resp1:", resp1, "resp2:", resp2)
	}

	client1.Close()
	client2.Close()
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值