Movatterモバイル変換


[0]ホーム

URL:


rpc

packagestandard library
go1.25.4Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2025 License:BSD-3-ClauseImports:14Imported by:17,986

Details

Repository

cs.opensource.google/go/go

Links

Documentation

Overview

Package rpc provides access to the exported methods of an object across anetwork or other I/O connection.

The net/rpc package is frozen and is not accepting new features.

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) error

where 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 byerrors.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 callingServeConn. Moretypically it will create a network listener and callAccept or, for an HTTPlistener,HandleHTTP andhttp.Serve.

A client wishing to use the service establishes a connection and then invokesNewClient on the connection. The convenience functionDial (DialHTTP) performsboth steps for a raw network connection (an HTTP connection). The resultingClient 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, packageencoding/gob is used totransport the data.

Here is a simple example. A server wishes to export an object of type Arith:

package serverimport "errors"type Args struct {A, B int}type Quotient struct {Quo, Rem int}type Arith intfunc (t *Arith) Multiply(args *Args, reply *int) error {*reply = args.A * args.Breturn 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.Bquo.Rem = args.A % args.Breturn 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 callargs := &server.Args{7,8}var reply interr = 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 callquotient := 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.

Index

Constants

View Source
const (// Defaults used by HandleHTTPDefaultRPCPath   = "/_goRPC_"DefaultDebugPath = "/debug/rpc")

Variables

View Source
var DefaultServer =NewServer()

DefaultServer is the default instance of*Server.

View Source
var ErrShutdown =errors.New("connection is shut down")

Functions

funcAccept

func Accept(lisnet.Listener)

Accept accepts connections on the listener and serves requeststoDefaultServer for each incoming connection.Accept blocks; the caller typically invokes it in a go statement.

funcHandleHTTP

func HandleHTTP()

HandleHTTP registers an HTTP handler for RPC messages toDefaultServeronDefaultRPCPath and a debugging handler onDefaultDebugPath.It is still necessary to invokehttp.Serve(), typically in a go statement.

funcRegister

func Register(rcvrany)error

Register publishes the receiver's methods in theDefaultServer.

funcRegisterName

func RegisterName(namestring, rcvrany)error

RegisterName is likeRegister but uses the provided name for the typeinstead of the receiver's concrete type.

funcServeCodec

func ServeCodec(codecServerCodec)

ServeCodec is likeServeConn but uses the specified codec todecode requests and encode responses.

funcServeConn

func ServeConn(connio.ReadWriteCloser)

ServeConn runs theDefaultServer 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 theconnection. To use an alternate codec, useServeCodec.SeeNewClient's comment for information about concurrent access.

funcServeRequest

func ServeRequest(codecServerCodec)error

ServeRequest is likeServeCodec but synchronously serves a single request.It does not close the codec upon completion.

Types

typeCall

type Call struct {ServiceMethodstring// The name of the service and method to call.Argsany// The argument to the function (*struct).Replyany// The reply from the function (*struct).Errorerror// After completion, the error status.Done          chan *Call// Receives *Call when Go is complete.}

Call represents an active RPC.

typeClient

type Client struct {// contains filtered or unexported fields}

Client represents an RPC Client.There may be multiple outstanding Calls associatedwith a single Client, and a Client may be used bymultiple goroutines simultaneously.

funcDial

func Dial(network, addressstring) (*Client,error)

Dial connects to an RPC server at the specified network address.

funcDialHTTP

func DialHTTP(network, addressstring) (*Client,error)

DialHTTP connects to an HTTP RPC server at the specified network addresslistening on the default HTTP RPC path.

funcDialHTTPPath

func DialHTTPPath(network, address, pathstring) (*Client,error)

DialHTTPPath connects to an HTTP RPC serverat the specified network address and path.

funcNewClient

func NewClient(connio.ReadWriteCloser) *Client

NewClient returns a newClient to handle requests to theset of services at the other end of the connection.It adds a buffer to the write side of the connection sothe header and payload are sent as a unit.

The read and write halves of the connection are serialized independently,so no interlocking is required. However each half may be accessedconcurrently so the implementation of conn should protect againstconcurrent reads or concurrent writes.

funcNewClientWithCodec

func NewClientWithCodec(codecClientCodec) *Client

NewClientWithCodec is likeNewClient but uses the specifiedcodec to encode requests and decode responses.

func (*Client)Call

func (client *Client) Call(serviceMethodstring, argsany, replyany)error

Call invokes the named function, waits for it to complete, and returns its error status.

func (*Client)Close

func (client *Client) Close()error

Close calls the underlying codec's Close method. If the connection is alreadyshutting down,ErrShutdown is returned.

func (*Client)Go

func (client *Client) Go(serviceMethodstring, argsany, replyany, done chan *Call) *Call

Go invokes the function asynchronously. It returns theCall structure representingthe invocation. The done channel will signal when the call is complete by returningthe same Call object. If done is nil, Go will allocate a new channel.If non-nil, done must be buffered or Go will deliberately crash.

typeClientCodec

type ClientCodec interface {WriteRequest(*Request,any)errorReadResponseHeader(*Response)errorReadResponseBody(any)errorClose()error}

A ClientCodec implements writing of RPC requests andreading of RPC responses for the client side of an RPC session.The client calls [ClientCodec.WriteRequest] to write a request to the connectionand calls [ClientCodec.ReadResponseHeader] and [ClientCodec.ReadResponseBody] in pairsto read responses. The client calls [ClientCodec.Close] when finished with theconnection. ReadResponseBody may be called with a nilargument to force the body of the response to be read and thendiscarded.SeeNewClient's comment for information about concurrent access.

typeRequest

type Request struct {ServiceMethodstring// format: "Service.Method"Sequint64// sequence number chosen by client// contains filtered or unexported fields}

Request is a header written before every RPC call. It is used internallybut documented here as an aid to debugging, such as when analyzingnetwork traffic.

typeResponse

type Response struct {ServiceMethodstring// echoes that of the RequestSequint64// echoes that of the requestErrorstring// error, if any.// contains filtered or unexported fields}

Response is a header written before every RPC return. It is used internallybut documented here as an aid to debugging, such as when analyzingnetwork traffic.

typeServer

type Server struct {// contains filtered or unexported fields}

Server represents an RPC Server.

funcNewServer

func NewServer() *Server

NewServer returns a newServer.

func (*Server)Accept

func (server *Server) Accept(lisnet.Listener)

Accept accepts connections on the listener and serves requestsfor each incoming connection. Accept blocks until the listenerreturns a non-nil error. The caller typically invokes Accept in ago statement.

func (*Server)HandleHTTP

func (server *Server) HandleHTTP(rpcPath, debugPathstring)

HandleHTTP registers an HTTP handler for RPC messages on rpcPath,and a debugging handler on debugPath.It is still necessary to invokehttp.Serve(), typically in a go statement.

func (*Server)Register

func (server *Server) Register(rcvrany)error

Register publishes in the server the set of methods of thereceiver 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 hasno 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)RegisterName

func (server *Server) RegisterName(namestring, rcvrany)error

RegisterName is likeRegister but uses the provided name for the typeinstead of the receiver's concrete type.

func (*Server)ServeCodec

func (server *Server) ServeCodec(codecServerCodec)

ServeCodec is likeServeConn but uses the specified codec todecode requests and encode responses.

func (*Server)ServeConn

func (server *Server) ServeConn(connio.ReadWriteCloser)

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 theconnection. To use an alternate codec, useServeCodec.SeeNewClient's comment for information about concurrent access.

func (*Server)ServeHTTP

func (server *Server) ServeHTTP(whttp.ResponseWriter, req *http.Request)

ServeHTTP implements anhttp.Handler that answers RPC requests.

func (*Server)ServeRequest

func (server *Server) ServeRequest(codecServerCodec)error

ServeRequest is likeServeCodec but synchronously serves a single request.It does not close the codec upon completion.

typeServerCodec

type ServerCodec interface {ReadRequestHeader(*Request)errorReadRequestBody(any)errorWriteResponse(*Response,any)error// Close can be called multiple times and must be idempotent.Close()error}

A ServerCodec implements reading of RPC requests and writing ofRPC responses for the server side of an RPC session.The server calls [ServerCodec.ReadRequestHeader] and [ServerCodec.ReadRequestBody] in pairsto read requests from the connection, and it calls [ServerCodec.WriteResponse] towrite a response back. The server calls [ServerCodec.Close] when finished with theconnection. ReadRequestBody may be called with a nilargument to force the body of the request to be read and discarded.SeeNewClient's comment for information about concurrent access.

typeServerError

type ServerErrorstring

ServerError represents an error that has been returned fromthe remote side of the RPC connection.

func (ServerError)Error

func (eServerError) Error()string

Source Files

View all Source files

Directories

PathSynopsis
Package jsonrpc implements a JSON-RPC 1.0 ClientCodec and ServerCodec for the rpc package.
Package jsonrpc implements a JSON-RPC 1.0 ClientCodec and ServerCodec for the rpc package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp