就贴一段代码…
package main
import (
"bytes"
"errors"
"io"
"log"
"net/http"
"net/rpc"
"net/rpc/jsonrpc"
)
type Args struct {
A, B int
}
type Quotient struct {
Quo, Rem int
}
type Arith int
func (t *Arith) Multiply(args *Args, reply *int) error {
*reply = args.A * args.B
return nil
}
func (t *Arith) Divide(args *Args, quo *Quotient) error {
if args.B == 0 {
return errors.New("divide by zero")
}
quo.Quo = args.A / args.B
quo.Rem = args.A % args.B
return nil
}
// rpcRequest represents a RPC request.
// rpcRequest implements the io.ReadWriteCloser interface.
type rpcRequest struct {
r io.Reader // holds the JSON formated RPC request
rw io.ReadWriter // holds the JSON formated RPC response
done chan bool // signals then end of the RPC request
}
// NewRPCRequest returns a new rpcRequest.
func NewRPCRequest(r io.Reader) *rpcRequest {
var buf bytes.Buffer
done := make(chan bool)
return &rpcRequest{r, &buf, done}
}
// Read implements the io.ReadWriteCloser Read method.
func (r *rpcRequest) Read(p []byte) (n int, err error) {
return r.r.Read(p)
}
// Write implements the io.ReadWriteCloser Write method.
func (r *rpcRequest) Write(p []byte) (n int, err error) {
return r.rw.Write(p)
}
// Close implements the io.ReadWriteCloser Close method.
func (r *rpcRequest) Close() error {
r.done <- true
return nil
}
// Call invokes the RPC request, waits for it to complete, and returns the results.
func (r *rpcRequest) Call() io.Reader {
go jsonrpc.ServeConn(r)
<-r.done
return r.rw
}
func main() {
arith := new(Arith)
rpc.Register(arith)
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
w.Header().Set("Content-Type", "application/json")
res := NewRPCRequest(req.Body).Call()
io.Copy(w, res)
})
log.Fatal(http.ListenAndServe(":8080", nil))
}