go-micro.dev/v5@v5.12.0/server/server.go (about)

     1  // Package server is an interface for a micro server
     2  package server
     3  
     4  import (
     5  	"context"
     6  	"os"
     7  	"os/signal"
     8  	"time"
     9  
    10  	"github.com/google/uuid"
    11  
    12  	"go-micro.dev/v5/codec"
    13  	log "go-micro.dev/v5/logger"
    14  	"go-micro.dev/v5/registry"
    15  	signalutil "go-micro.dev/v5/util/signal"
    16  )
    17  
    18  // Server is a simple micro server abstraction.
    19  type Server interface {
    20  	// Initialize options
    21  	Init(...Option) error
    22  	// Retrieve the options
    23  	Options() Options
    24  	// Register a handler
    25  	Handle(Handler) error
    26  	// Create a new handler
    27  	NewHandler(interface{}, ...HandlerOption) Handler
    28  	// Create a new subscriber
    29  	NewSubscriber(string, interface{}, ...SubscriberOption) Subscriber
    30  	// Register a subscriber
    31  	Subscribe(Subscriber) error
    32  	// Start the server
    33  	Start() error
    34  	// Stop the server
    35  	Stop() error
    36  	// Server implementation
    37  	String() string
    38  }
    39  
    40  // Router handle serving messages.
    41  type Router interface {
    42  	// ProcessMessage processes a message
    43  	ProcessMessage(context.Context, string, Message) error
    44  	// ServeRequest processes a request to completion
    45  	ServeRequest(context.Context, Request, Response) error
    46  }
    47  
    48  // Message is an async message interface.
    49  type Message interface {
    50  	// Topic of the message
    51  	Topic() string
    52  	// The decoded payload value
    53  	Payload() interface{}
    54  	// The content type of the payload
    55  	ContentType() string
    56  	// The raw headers of the message
    57  	Header() map[string]string
    58  	// The raw body of the message
    59  	Body() []byte
    60  	// Codec used to decode the message
    61  	Codec() codec.Reader
    62  }
    63  
    64  // Request is a synchronous request interface.
    65  type Request interface {
    66  	// Service name requested
    67  	Service() string
    68  	// The action requested
    69  	Method() string
    70  	// Endpoint name requested
    71  	Endpoint() string
    72  	// Content type provided
    73  	ContentType() string
    74  	// Header of the request
    75  	Header() map[string]string
    76  	// Body is the initial decoded value
    77  	Body() interface{}
    78  	// Read the undecoded request body
    79  	Read() ([]byte, error)
    80  	// The encoded message stream
    81  	Codec() codec.Reader
    82  	// Indicates whether its a stream
    83  	Stream() bool
    84  }
    85  
    86  // Response is the response writer for unencoded messages.
    87  type Response interface {
    88  	// Encoded writer
    89  	Codec() codec.Writer
    90  	// Write the header
    91  	WriteHeader(map[string]string)
    92  	// write a response directly to the client
    93  	Write([]byte) error
    94  }
    95  
    96  // Stream represents a stream established with a client.
    97  // A stream can be bidirectional which is indicated by the request.
    98  // The last error will be left in Error().
    99  // EOF indicates end of the stream.
   100  type Stream interface {
   101  	Context() context.Context
   102  	Request() Request
   103  	Send(interface{}) error
   104  	Recv(interface{}) error
   105  	Error() error
   106  	Close() error
   107  }
   108  
   109  // Handler interface represents a request handler. It's generated
   110  // by passing any type of public concrete object with endpoints into server.NewHandler.
   111  // Most will pass in a struct.
   112  //
   113  // Example:
   114  //
   115  //	type Greeter struct {}
   116  //
   117  //	func (g *Greeter) Hello(context, request, response) error {
   118  //	        return nil
   119  //	}
   120  type Handler interface {
   121  	Name() string
   122  	Handler() interface{}
   123  	Endpoints() []*registry.Endpoint
   124  	Options() HandlerOptions
   125  }
   126  
   127  // Subscriber interface represents a subscription to a given topic using
   128  // a specific subscriber function or object with endpoints. It mirrors
   129  // the handler in its behavior.
   130  type Subscriber interface {
   131  	Topic() string
   132  	Subscriber() interface{}
   133  	Endpoints() []*registry.Endpoint
   134  	Options() SubscriberOptions
   135  }
   136  
   137  type Option func(*Options)
   138  
   139  var (
   140  	DefaultAddress                 = ":0"
   141  	DefaultName                    = "go.micro.server"
   142  	DefaultVersion                 = "latest"
   143  	DefaultId                      = uuid.New().String()
   144  	DefaultServer           Server = NewRPCServer()
   145  	DefaultRouter                  = newRpcRouter()
   146  	DefaultRegisterCheck           = func(context.Context) error { return nil }
   147  	DefaultRegisterInterval        = time.Second * 30
   148  	DefaultRegisterTTL             = time.Second * 90
   149  
   150  	// NewServer creates a new server.
   151  	NewServer func(...Option) Server = NewRPCServer
   152  )
   153  
   154  // DefaultOptions returns config options for the default service.
   155  func DefaultOptions() Options {
   156  	return DefaultServer.Options()
   157  }
   158  
   159  func Init(opt ...Option) {
   160  	if DefaultServer == nil {
   161  		DefaultServer = NewRPCServer(opt...)
   162  	}
   163  	DefaultServer.Init(opt...)
   164  }
   165  
   166  // NewRouter returns a new router.
   167  func NewRouter() *router {
   168  	return newRpcRouter()
   169  }
   170  
   171  // NewSubscriber creates a new subscriber interface with the given topic
   172  // and handler using the default server.
   173  func NewSubscriber(topic string, h interface{}, opts ...SubscriberOption) Subscriber {
   174  	return DefaultServer.NewSubscriber(topic, h, opts...)
   175  }
   176  
   177  // NewHandler creates a new handler interface using the default server
   178  // Handlers are required to be a public object with public
   179  // endpoints. Call to a service endpoint such as Foo.Bar expects
   180  // the type:
   181  //
   182  //	type Foo struct {}
   183  //	func (f *Foo) Bar(ctx, req, rsp) error {
   184  //		return nil
   185  //	}
   186  func NewHandler(h interface{}, opts ...HandlerOption) Handler {
   187  	return DefaultServer.NewHandler(h, opts...)
   188  }
   189  
   190  // Handle registers a handler interface with the default server to
   191  // handle inbound requests.
   192  func Handle(h Handler) error {
   193  	return DefaultServer.Handle(h)
   194  }
   195  
   196  // Subscribe registers a subscriber interface with the default server
   197  // which subscribes to specified topic with the broker.
   198  func Subscribe(s Subscriber) error {
   199  	return DefaultServer.Subscribe(s)
   200  }
   201  
   202  // Run starts the default server and waits for a kill
   203  // signal before exiting. Also registers/deregisters the server.
   204  func Run() error {
   205  	if err := Start(); err != nil {
   206  		return err
   207  	}
   208  
   209  	ch := make(chan os.Signal, 1)
   210  	signal.Notify(ch, signalutil.Shutdown()...)
   211  	DefaultServer.Options().Logger.Logf(log.InfoLevel, "Received signal %s", <-ch)
   212  
   213  	return Stop()
   214  }
   215  
   216  // Start starts the default server.
   217  func Start() error {
   218  	config := DefaultServer.Options()
   219  	config.Logger.Logf(log.InfoLevel, "Starting server %s id %s", config.Name, config.Id)
   220  	return DefaultServer.Start()
   221  }
   222  
   223  // Stop stops the default server.
   224  func Stop() error {
   225  	DefaultServer.Options().Logger.Logf(log.InfoLevel, "Stopping server")
   226  	return DefaultServer.Stop()
   227  }
   228  
   229  // String returns name of Server implementation.
   230  func String() string {
   231  	return DefaultServer.String()
   232  }