// Copyright 2009 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.
/*Package rpc provides access to the exported methods of an object across anetwork or other I/O connection. A server registers an object, making it visibleas a service with the name of the type of the object. After registration, exportedmethods of the object will be accessible remotely. A server may register multipleobjects (services) of different types but it is an error to register multipleobjects of the same type.Only methods that satisfy these criteria will be made available for remote access;other methods will be ignored: - the method's type is exported. - the method is exported. - the method has two arguments, both exported (or builtin) types. - the method's second argument is a pointer. - the method has return type error.In effect, the method must look schematically like func (t *T) MethodName(argType T1, replyType *T2) errorwhere T1 and T2 can be marshaled by encoding/gob.These requirements apply even if a different codec is used.(In the future, these requirements may soften for custom codecs.)The method's first argument represents the arguments provided by the caller; thesecond argument represents the result parameters to be returned to the caller.The method's return value, if non-nil, is passed back as a string that the clientsees as if created by [errors.New]. If an error is returned, the reply parameterwill not be sent back to the client.The server may handle requests on a single connection by calling [ServeConn]. Moretypically it will create a network listener and call [Accept] or, for an HTTPlistener, [HandleHTTP] and [http.Serve].A client wishing to use the service establishes a connection and then invokes[NewClient] on the connection. The convenience function [Dial] ([DialHTTP]) performsboth steps for a raw network connection (an HTTP connection). The resulting[Client] object has two methods, [Call] and Go, that specify the service and method tocall, a pointer containing the arguments, and a pointer to receive the resultparameters.The Call method waits for the remote call to complete while the Go methodlaunches the call asynchronously and signals completion using the Callstructure's Done channel.Unless an explicit codec is set up, package [encoding/gob] is used totransport the data.Here is a simple example. A server wishes to export an object of type Arith: package server import "errors" 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 }The server calls (for HTTP service): arith := new(Arith) rpc.Register(arith) rpc.HandleHTTP() l, err := net.Listen("tcp", ":1234") if err != nil { log.Fatal("listen error:", err) } go http.Serve(l, nil)At this point, clients can see a service "Arith" with methods "Arith.Multiply" and"Arith.Divide". To invoke one, a client first dials the server: client, err := rpc.DialHTTP("tcp", serverAddress + ":1234") if err != nil { log.Fatal("dialing:", err) }Then it can make a remote call: // Synchronous call args := &server.Args{7,8} var reply int err = client.Call("Arith.Multiply", args, &reply) if err != nil { log.Fatal("arith error:", err) } fmt.Printf("Arith: %d*%d=%d", args.A, args.B, reply)or // Asynchronous call quotient := new(Quotient) divCall := client.Go("Arith.Divide", args, quotient, nil) replyCall := <-divCall.Done // will be equal to divCall // check errors, print, etc.A server implementation will often provide a simple, type-safe wrapper for theclient.The net/rpc package is frozen and is not accepting new features.*/
package rpcimport ()const (// Defaults used by HandleHTTPDefaultRPCPath = "/_goRPC_"DefaultDebugPath = "/debug/rpc")// Precompute the reflect type for error.var typeOfError = reflect.TypeFor[error]()type methodType struct {sync.Mutex// protects counters method reflect.Method ArgType reflect.Type ReplyType reflect.Type numCalls uint}type service struct { name string// name of service rcvr reflect.Value// receiver of methods for the service typ reflect.Type// type of the receiver method map[string]*methodType// registered methods}// Request is a header written before every RPC call. It is used internally// but documented here as an aid to debugging, such as when analyzing// network traffic.typeRequeststruct { ServiceMethod string// format: "Service.Method" Seq uint64// sequence number chosen by client next *Request// for free list in Server}// Response is a header written before every RPC return. It is used internally// but documented here as an aid to debugging, such as when analyzing// network traffic.typeResponsestruct { ServiceMethod string// echoes that of the Request Seq uint64// echoes that of the request Error string// error, if any. next *Response// for free list in Server}// Server represents an RPC Server.typeServerstruct { serviceMap sync.Map// map[string]*service reqLock sync.Mutex// protects freeReq freeReq *Request respLock sync.Mutex// protects freeResp freeResp *Response}// NewServer returns a new [Server].func () *Server {return &Server{}}// DefaultServer is the default instance of [*Server].varDefaultServer = NewServer()// Is this type exported or a builtin?func isExportedOrBuiltinType( reflect.Type) bool {for .Kind() == reflect.Pointer { = .Elem() }// PkgPath will be non-empty even for an exported type, // so we need to check the type name as well.returntoken.IsExported(.Name()) || .PkgPath() == ""}// Register publishes in the server the set of methods of the// receiver value that satisfy the following conditions:// - exported method of exported type// - two arguments, both of exported type// - the second argument is a pointer// - one return value, of type error//// It returns an error if the receiver is not an exported type or has// no suitable methods. It also logs the error using package log.// The client accesses each method using a string of the form "Type.Method",// where Type is the receiver's concrete type.func ( *Server) ( any) error {return .register(, "", false)}// RegisterName is like [Register] but uses the provided name for the type// instead of the receiver's concrete type.func ( *Server) ( string, any) error {return .register(, , true)}// logRegisterError specifies whether to log problems during method registration.// To debug registration, recompile the package with this set to true.const logRegisterError = falsefunc ( *Server) ( any, string, bool) error { := new(service) .typ = reflect.TypeOf() .rcvr = reflect.ValueOf() := if ! { = reflect.Indirect(.rcvr).Type().Name() }if == "" { := "rpc.Register: no service name for type " + .typ.String()log.Print()returnerrors.New() }if ! && !token.IsExported() { := "rpc.Register: type " + + " is not exported"log.Print()returnerrors.New() } .name = // Install the methods .method = suitableMethods(.typ, logRegisterError)iflen(.method) == 0 { := ""// To help the user, see if a pointer receiver would work. := suitableMethods(reflect.PointerTo(.typ), false)iflen() != 0 { = "rpc.Register: type " + + " has no exported methods of suitable type (hint: pass a pointer to value of that type)" } else { = "rpc.Register: type " + + " has no exported methods of suitable type" }log.Print()returnerrors.New() }if , := .serviceMap.LoadOrStore(, ); {returnerrors.New("rpc: service already defined: " + ) }returnnil}// suitableMethods returns suitable Rpc methods of typ. It will log// errors if logErr is true.func suitableMethods( reflect.Type, bool) map[string]*methodType { := make(map[string]*methodType)for := 0; < .NumMethod(); ++ { := .Method() := .Type := .Name// Method must be exported.if !.IsExported() {continue }// Method needs three ins: receiver, *args, *reply.if .NumIn() != 3 {if {log.Printf("rpc.Register: method %q has %d input parameters; needs exactly three\n", , .NumIn()) }continue }// First arg need not be a pointer. := .In(1)if !isExportedOrBuiltinType() {if {log.Printf("rpc.Register: argument type of method %q is not exported: %q\n", , ) }continue }// Second arg must be a pointer. := .In(2)if .Kind() != reflect.Pointer {if {log.Printf("rpc.Register: reply type of method %q is not a pointer: %q\n", , ) }continue }// Reply type must be exported.if !isExportedOrBuiltinType() {if {log.Printf("rpc.Register: reply type of method %q is not exported: %q\n", , ) }continue }// Method needs one out.if .NumOut() != 1 {if {log.Printf("rpc.Register: method %q has %d output parameters; needs exactly one\n", , .NumOut()) }continue }// The return type of the method must be error.if := .Out(0); != typeOfError {if {log.Printf("rpc.Register: return type of method %q is %q, must be error\n", , ) }continue } [] = &methodType{method: , ArgType: , ReplyType: } }return}// A value sent as a placeholder for the server's response value when the server// receives an invalid request. It is never decoded by the client since the Response// contains an error when it is used.var invalidRequest = struct{}{}func ( *Server) ( *sync.Mutex, *Request, any, ServerCodec, string) { := .getResponse()// Encode the response header .ServiceMethod = .ServiceMethodif != "" { .Error = = invalidRequest } .Seq = .Seq .Lock() := .WriteResponse(, )ifdebugLog && != nil {log.Println("rpc: writing response:", ) } .Unlock() .freeResponse()}func ( *methodType) () ( uint) { .Lock() = .numCalls .Unlock()return}func ( *service) ( *Server, *sync.Mutex, *sync.WaitGroup, *methodType, *Request, , reflect.Value, ServerCodec) {if != nil {defer .Done() } .Lock() .numCalls++ .Unlock() := .method.Func// Invoke the method, providing a new value for the reply. := .Call([]reflect.Value{.rcvr, , })// The return value for the method is an error. := [0].Interface() := ""if != nil { = .(error).Error() } .sendResponse(, , .Interface(), , ) .freeRequest()}type gobServerCodec struct { rwc io.ReadWriteCloser dec *gob.Decoder enc *gob.Encoder encBuf *bufio.Writer closed bool}func ( *gobServerCodec) ( *Request) error {return .dec.Decode()}func ( *gobServerCodec) ( any) error {return .dec.Decode()}func ( *gobServerCodec) ( *Response, any) ( error) {if = .enc.Encode(); != nil {if .encBuf.Flush() == nil {// Gob couldn't encode the header. Should not happen, so if it does, // shut down the connection to signal that the connection is broken.log.Println("rpc: gob error encoding response:", ) .Close() }return }if = .enc.Encode(); != nil {if .encBuf.Flush() == nil {// Was a gob problem encoding the body but the header has been written. // Shut down the connection to signal that the connection is broken.log.Println("rpc: gob error encoding body:", ) .Close() }return }return .encBuf.Flush()}func ( *gobServerCodec) () error {if .closed {// Only call c.rwc.Close once; otherwise the semantics are undefined.returnnil } .closed = truereturn .rwc.Close()}// ServeConn runs the server on a single connection.// ServeConn blocks, serving the connection until the client hangs up.// The caller typically invokes ServeConn in a go statement.// ServeConn uses the gob wire format (see package gob) on the// connection. To use an alternate codec, use [ServeCodec].// See [NewClient]'s comment for information about concurrent access.func ( *Server) ( io.ReadWriteCloser) { := bufio.NewWriter() := &gobServerCodec{rwc: ,dec: gob.NewDecoder(),enc: gob.NewEncoder(),encBuf: , } .ServeCodec()}// ServeCodec is like [ServeConn] but uses the specified codec to// decode requests and encode responses.func ( *Server) ( ServerCodec) { := new(sync.Mutex) := new(sync.WaitGroup)for { , , , , , , := .readRequest()if != nil {ifdebugLog && != io.EOF {log.Println("rpc:", ) }if ! {break }// send a response if we actually managed to read a header.if != nil { .sendResponse(, , invalidRequest, , .Error()) .freeRequest() }continue } .Add(1)go .call(, , , , , , , ) }// We've seen that there are no more requests. // Wait for responses to be sent before closing codec. .Wait() .Close()}// ServeRequest is like [ServeCodec] but synchronously serves a single request.// It does not close the codec upon completion.func ( *Server) ( ServerCodec) error { := new(sync.Mutex) , , , , , , := .readRequest()if != nil {if ! {return }// send a response if we actually managed to read a header.if != nil { .sendResponse(, , invalidRequest, , .Error()) .freeRequest() }return } .call(, , nil, , , , , )returnnil}func ( *Server) () *Request { .reqLock.Lock() := .freeReqif == nil { = new(Request) } else { .freeReq = .next * = Request{} } .reqLock.Unlock()return}func ( *Server) ( *Request) { .reqLock.Lock() .next = .freeReq .freeReq = .reqLock.Unlock()}func ( *Server) () *Response { .respLock.Lock() := .freeRespif == nil { = new(Response) } else { .freeResp = .next * = Response{} } .respLock.Unlock()return}func ( *Server) ( *Response) { .respLock.Lock() .next = .freeResp .freeResp = .respLock.Unlock()}func ( *Server) ( ServerCodec) ( *service, *methodType, *Request, , reflect.Value, bool, error) { , , , , = .readRequestHeader()if != nil {if ! {return }// discard body .ReadRequestBody(nil)return }// Decode the argument value. := false// if true, need to indirect before calling.if .ArgType.Kind() == reflect.Pointer { = reflect.New(.ArgType.Elem()) } else { = reflect.New(.ArgType) = true }// argv guaranteed to be a pointer now.if = .ReadRequestBody(.Interface()); != nil {return }if { = .Elem() } = reflect.New(.ReplyType.Elem())switch .ReplyType.Elem().Kind() {casereflect.Map: .Elem().Set(reflect.MakeMap(.ReplyType.Elem()))casereflect.Slice: .Elem().Set(reflect.MakeSlice(.ReplyType.Elem(), 0, 0)) }return}func ( *Server) ( ServerCodec) ( *service, *methodType, *Request, bool, error) {// Grab the request header. = .getRequest() = .ReadRequestHeader()if != nil { = nilif == io.EOF || == io.ErrUnexpectedEOF {return } = errors.New("rpc: server cannot decode request: " + .Error())return }// We read the header successfully. If we see an error now, // we can still recover and move on to the next request. = true := strings.LastIndex(.ServiceMethod, ".")if < 0 { = errors.New("rpc: service/method request ill-formed: " + .ServiceMethod)return } := .ServiceMethod[:] := .ServiceMethod[+1:]// Look up the request. , := .serviceMap.Load()if ! { = errors.New("rpc: can't find service " + .ServiceMethod)return } = .(*service) = .method[]if == nil { = errors.New("rpc: can't find method " + .ServiceMethod) }return}// Accept accepts connections on the listener and serves requests// for each incoming connection. Accept blocks until the listener// returns a non-nil error. The caller typically invokes Accept in a// go statement.func ( *Server) ( net.Listener) {for { , := .Accept()if != nil {log.Print("rpc.Serve: accept:", .Error())return }go .ServeConn() }}// Register publishes the receiver's methods in the [DefaultServer].func ( any) error { returnDefaultServer.Register() }// RegisterName is like [Register] but uses the provided name for the type// instead of the receiver's concrete type.func ( string, any) error {returnDefaultServer.RegisterName(, )}// A ServerCodec implements reading of RPC requests and writing of// RPC responses for the server side of an RPC session.// The server calls [ServerCodec.ReadRequestHeader] and [ServerCodec.ReadRequestBody] in pairs// to read requests from the connection, and it calls [ServerCodec.WriteResponse] to// write a response back. The server calls [ServerCodec.Close] when finished with the// connection. ReadRequestBody may be called with a nil// argument to force the body of the request to be read and discarded.// See [NewClient]'s comment for information about concurrent access.typeServerCodecinterface {ReadRequestHeader(*Request) errorReadRequestBody(any) errorWriteResponse(*Response, any) error// Close can be called multiple times and must be idempotent.Close() error}// ServeConn runs the [DefaultServer] on a single connection.// ServeConn blocks, serving the connection until the client hangs up.// The caller typically invokes ServeConn in a go statement.// ServeConn uses the gob wire format (see package gob) on the// connection. To use an alternate codec, use [ServeCodec].// See [NewClient]'s comment for information about concurrent access.func ( io.ReadWriteCloser) {DefaultServer.ServeConn()}// ServeCodec is like [ServeConn] but uses the specified codec to// decode requests and encode responses.func ( ServerCodec) {DefaultServer.ServeCodec()}// ServeRequest is like [ServeCodec] but synchronously serves a single request.// It does not close the codec upon completion.func ( ServerCodec) error {returnDefaultServer.ServeRequest()}// Accept accepts connections on the listener and serves requests// to [DefaultServer] for each incoming connection.// Accept blocks; the caller typically invokes it in a go statement.func ( net.Listener) { DefaultServer.Accept() }// Can connect to RPC service using HTTP CONNECT to rpcPath.var connected = "200 Connected to Go RPC"// ServeHTTP implements an [http.Handler] that answers RPC requests.func ( *Server) ( http.ResponseWriter, *http.Request) {if .Method != "CONNECT" { .Header().Set("Content-Type", "text/plain; charset=utf-8") .WriteHeader(http.StatusMethodNotAllowed)io.WriteString(, "405 must CONNECT\n")return } , , := .(http.Hijacker).Hijack()if != nil {log.Print("rpc hijacking ", .RemoteAddr, ": ", .Error())return }io.WriteString(, "HTTP/1.0 "+connected+"\n\n") .ServeConn()}// HandleHTTP registers an HTTP handler for RPC messages on rpcPath,// and a debugging handler on debugPath.// It is still necessary to invoke [http.Serve](), typically in a go statement.func ( *Server) (, string) {http.Handle(, )http.Handle(, debugHTTP{})}// HandleHTTP registers an HTTP handler for RPC messages to [DefaultServer]// on [DefaultRPCPath] and a debugging handler on [DefaultDebugPath].// It is still necessary to invoke [http.Serve](), typically in a go statement.func () {DefaultServer.HandleHTTP(DefaultRPCPath, DefaultDebugPath)}
The pages are generated with Goldsv0.7.0-preview. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.