type Calculator int func (c *Calculator) Add(args *[]int, reply *int) error { sum := 0 for _, n := range *args { sum += n } *reply = sum return nil } func main() { calc := new(Calculator) server := rpc.NewServer() server.Register(calc) l, err := net.Listen("tcp", ":1234") if err != nil { log.Fatal("listen error:", err) } for { conn, err := l.Accept() if err != nil { log.Fatal("accept error:", err) } go server.ServeConn(conn) } }
type Math int func (m *Math) Multiply(args *[]int, reply *int) error { product := 1 for _, n := range *args { product *= n } *reply = product return nil } func main() { math := new(Math) rpc.Register(math) rpc.HandleHTTP() l, err := net.Listen("tcp", ":1234") if err != nil { log.Fatal("listen error:", err) } http.Serve(l, nil) }In the above example, we have defined a Math struct and its Multiply method to perform multiplication of integers. We then register our Math service using rpc.Register() and wrap our server with HTTP using the rpc.HandleHTTP() method. We listen for incoming connections on port 1234 and serve them using the http.Serve() method.