diff --git a/.golangci.yaml b/.golangci.yaml index e975fba648..1a7870502f 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -60,7 +60,7 @@ linters-settings: # The longest distance, in source lines, that is being considered a "small scope". # Variables used in at most this many lines will be ignored. # Default: 5 - max-distance: 16 + max-distance: 26 ignore-names: - err - id @@ -86,7 +86,7 @@ linters-settings: check-blank: true govet: # report about shadowed variables - check-shadowing: true + check-shadowing: false gofmt: # simplify code: gofmt with `-s` option, true by default simplify: true @@ -182,6 +182,7 @@ linters: - nonamedreturns - makezero - gofumpt + - nlreturn # Can be considered to be enabled - gochecknoinits diff --git a/api/api.go b/api/api.go index 996ead4146..be267221d8 100644 --- a/api/api.go +++ b/api/api.go @@ -12,10 +12,10 @@ import ( "go-micro.dev/v4/server" ) -// The gateway interface provides a way to -// create composable API gateways +// API interface provides a way to +// create composable API gateways. type Api interface { - // Initialise options + // Initialize options Init(...Option) error // Get the options Options() Options @@ -29,6 +29,7 @@ type Api interface { String() string } +// Options are API options. type Options struct { // Address of the server Address string @@ -36,9 +37,10 @@ type Options struct { Router router.Router } +// Option type are API option args. type Option func(*Options) error -// Endpoint is a mapping between an RPC method and HTTP endpoint +// Endpoint is a mapping between an RPC method and HTTP endpoint. type Endpoint struct { // RPC Method e.g. Greeter.Hello Name string @@ -56,7 +58,7 @@ type Endpoint struct { Stream bool } -// Service represents an API service +// Service represents an API service. type Service struct { // Name of service Name string @@ -82,21 +84,22 @@ func slice(s string) []string { return sl } -// Encode encodes an endpoint to endpoint metadata +// Encode encodes an endpoint to endpoint metadata. func Encode(e *Endpoint) map[string]string { if e == nil { return nil } // endpoint map - ep := make(map[string]string) + em := make(map[string]string) // set vals only if they exist set := func(k, v string) { if len(v) == 0 { return } - ep[k] = v + + em[k] = v } set("endpoint", e.Name) @@ -106,10 +109,10 @@ func Encode(e *Endpoint) map[string]string { set("path", strings.Join(e.Path, ",")) set("host", strings.Join(e.Host, ",")) - return ep + return em } -// Decode decodes endpoint metadata into an endpoint +// Decode decodes endpoint metadata into an endpoint. func Decode(e map[string]string) *Endpoint { if e == nil { return nil @@ -125,7 +128,7 @@ func Decode(e map[string]string) *Endpoint { } } -// Validate validates an endpoint to guarantee it won't blow up when being served +// Validate validates an endpoint to guarantee it won't blow up when being served. func Validate(e *Endpoint) error { if e == nil { return errors.New("endpoint is nil") @@ -172,7 +175,7 @@ func WithEndpoint(e *Endpoint) server.HandlerOption { return server.EndpointMetadata(e.Name, Encode(e)) } -// NewApi returns a new api gateway +// NewApi returns a new api gateway. func NewApi(opts ...Option) Api { return newApi(opts...) } diff --git a/api/api_test.go b/api/api_test.go index 2b3957e588..f515ddfecc 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -148,5 +148,4 @@ func TestValidate(t *testing.T) { if err := Validate(epPcreInvalid); err == nil { t.Fatalf("invalid pcre %v", epPcreInvalid.Path[0]) } - } diff --git a/api/client/client.go b/api/client/client.go index 00ed3f8a03..6f6d3bf14a 100644 --- a/api/client/client.go +++ b/api/client/client.go @@ -12,14 +12,16 @@ import ( "time" "github.com/gorilla/websocket" + + "go-micro.dev/v4/logger" ) const ( - // local address for api + // local address for api. localAddress = "http://localhost:8080" ) -// Options of the Client +// Options of the Client. type Options struct { // Token for authentication Token string @@ -33,7 +35,7 @@ type Options struct { Timeout time.Duration } -// Request is the request of the generic `api-client` call +// Request is the request of the generic `api-client` call. type Request struct { // eg. "go.micro.srv.greeter" Service string `json:"service"` @@ -55,17 +57,18 @@ type Response struct { Status string `json:"status"` } -// Client enables generic calls to micro +// Client enables generic calls to micro. type Client struct { options Options } +// Stream is a websockets stream. type Stream struct { conn *websocket.Conn service, endpoint string } -// NewClient returns a generic micro client that connects to live by default +// NewClient returns a generic micro client that connects to live by default. func NewClient(options *Options) *Client { ret := new(Client) ret.options = Options{ @@ -93,17 +96,17 @@ func NewClient(options *Options) *Client { return ret } -// SetToken sets the api auth token +// SetToken sets the api auth token. func (client *Client) SetToken(t string) { client.options.Token = t } -// SetTimeout sets the http client's timeout +// SetTimeout sets the http client's timeout. func (client *Client) SetTimeout(d time.Duration) { client.options.Timeout = d } -// Call enables you to access any endpoint of any service on Micro +// Call enables you to access any endpoint of any service on Micro. func (client *Client) Call(service, endpoint string, request, response interface{}) error { // example curl: curl -XPOST -d '{"service": "go.micro.srv.greeter", "endpoint": "Say.Hello"}' // -H 'Content-Type: application/json' http://localhost:8080/client {"body":"eyJtc2ciOiJIZWxsbyAifQ=="} @@ -115,7 +118,7 @@ func (client *Client) Call(service, endpoint string, request, response interface // set the url to go through the v1 api uri.Path = "/" + service + "/" + endpoint - b, err := marshalRequest(service, endpoint, request) + b, err := marshalRequest(endpoint, request) if err != nil { return err } @@ -141,21 +144,28 @@ func (client *Client) Call(service, endpoint string, request, response interface if err != nil { return err } - defer resp.Body.Close() + + defer func() { + if err = resp.Body.Close(); err != nil { + logger.DefaultLogger.Log(logger.ErrorLevel, err) + } + }() body, err := ioutil.ReadAll(resp.Body) if err != nil { return err } - if !(resp.StatusCode >= 200 && resp.StatusCode < 300) { + + if resp.StatusCode <= 200 || resp.StatusCode > 300 { return errors.New(string(body)) } + return unmarshalResponse(body, response) } -// Stream enables the ability to stream via websockets +// Stream enables the ability to stream via websockets. func (client *Client) Stream(service, endpoint string, request interface{}) (*Stream, error) { - b, err := marshalRequest(service, endpoint, request) + b, err := marshalRequest(endpoint, request) if err != nil { return nil, err } @@ -177,9 +187,10 @@ func (client *Client) Stream(service, endpoint string, request interface{}) (*St if len(client.options.Token) > 0 { header.Set("Authorization", "Bearer "+client.options.Token) } + header.Set("Content-Type", "application/json") - // dial the connection + // dial the connection, connection not closed as conn is returned conn, _, err := websocket.DefaultDialer.Dial(uri.String(), header) if err != nil { return nil, err @@ -193,24 +204,28 @@ func (client *Client) Stream(service, endpoint string, request interface{}) (*St return &Stream{conn, service, endpoint}, nil } +// Recv will receive a message from a stream and unmarshal it. func (s *Stream) Recv(v interface{}) error { // read response _, message, err := s.conn.ReadMessage() if err != nil { return err } + return unmarshalResponse(message, v) } +// Send will send a message into the stream. func (s *Stream) Send(v interface{}) error { - b, err := marshalRequest(s.service, s.endpoint, v) + b, err := marshalRequest(s.endpoint, v) if err != nil { return err } + return s.conn.WriteMessage(websocket.TextMessage, b) } -func marshalRequest(service, endpoint string, v interface{}) ([]byte, error) { +func marshalRequest(endpoint string, v interface{}) ([]byte, error) { return json.Marshal(v) } diff --git a/api/default.go b/api/default.go index c4c111f739..e202eb5c30 100644 --- a/api/default.go +++ b/api/default.go @@ -45,7 +45,6 @@ func newApi(opts ...Option) Api { } } -// Initialise options func (a *api) Init(opts ...Option) error { for _, o := range opts { o(&a.options) @@ -53,17 +52,17 @@ func (a *api) Init(opts ...Option) error { return nil } -// Get the options +// Get the options. func (a *api) Options() Options { return a.options } -// Register a http handler +// Register a http handler. func (a *api) Register(*Endpoint) error { return nil } -// Register a route +// Register a route. func (a *api) Deregister(*Endpoint) error { return nil } diff --git a/api/handler/api/api.go b/api/handler/api/api.go index 4c52daab9e..b8cebdae17 100644 --- a/api/handler/api/api.go +++ b/api/handler/api/api.go @@ -21,7 +21,7 @@ const ( Handler = "api" ) -// API handler is the default handler which takes api.Request and returns api.Response +// API handler is the default handler which takes api.Request and returns api.Response. func (a *apiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { bsize := handler.DefaultMaxRecvSize if a.opts.MaxRecvSize > 0 { diff --git a/api/handler/api/util.go b/api/handler/api/util.go index 72824805a1..2da471c930 100644 --- a/api/handler/api/util.go +++ b/api/handler/api/util.go @@ -14,7 +14,7 @@ import ( ) var ( - // need to calculate later to specify useful defaults + // need to calculate later to specify useful defaults. bufferPool = bpool.NewSizedBufferPool(1024, 8) ) @@ -34,11 +34,11 @@ func requestToProto(r *http.Request) (*api.Request, error) { ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) if err != nil { - ct = "text/plain; charset=UTF-8" //default CT is text/plain + ct = "text/plain; charset=UTF-8" // default CT is text/plain r.Header.Set("Content-Type", ct) } - //set the body: + // set the body: if r.Body != nil { switch ct { case "application/x-www-form-urlencoded": @@ -110,7 +110,7 @@ func requestToProto(r *http.Request) (*api.Request, error) { return req, nil } -// strategy is a hack for selection +// strategy is a hack for selection. func strategy(services []*registry.Service) selector.Strategy { return func(_ []*registry.Service) selector.Next { // ignore input to this function, use services above diff --git a/api/handler/handler.go b/api/handler/handler.go index ece71b5723..72f9c23e8a 100644 --- a/api/handler/handler.go +++ b/api/handler/handler.go @@ -5,7 +5,7 @@ import ( "net/http" ) -// Handler represents a HTTP handler that manages a request +// Handler represents a HTTP handler that manages a request. type Handler interface { // standard http handler http.Handler diff --git a/api/handler/http/http.go b/api/handler/http/http.go index 6155643f97..520078b561 100644 --- a/api/handler/http/http.go +++ b/api/handler/http/http.go @@ -42,7 +42,7 @@ func (h *httpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { httputil.NewSingleHostReverseProxy(rp).ServeHTTP(w, r) } -// getService returns the service for this request from the selector +// getService returns the service for this request from the selector. func (h *httpHandler) getService(r *http.Request) (string, error) { var service *router.Route @@ -74,7 +74,7 @@ func (h *httpHandler) String() string { return "http" } -// NewHandler returns a http proxy handler +// NewHandler returns a http proxy handler. func NewHandler(opts ...handler.Option) handler.Handler { options := handler.NewOptions(opts...) diff --git a/api/handler/http/http_test.go b/api/handler/http/http_test.go index 8c44983e92..d7424e7c2e 100644 --- a/api/handler/http/http_test.go +++ b/api/handler/http/http_test.go @@ -52,7 +52,7 @@ func testHttp(t *testing.T, path, service, ns string) { t.Fatal(err) } - // initialise the handler + // initialize the handler rt := regRouter.NewRouter( router.WithHandler("http"), router.WithRegistry(r), diff --git a/api/handler/options.go b/api/handler/options.go index aa647df104..1e7efd7306 100644 --- a/api/handler/options.go +++ b/api/handler/options.go @@ -20,7 +20,7 @@ type Options struct { type Option func(o *Options) -// NewOptions fills in the blanks +// NewOptions fills in the blanks. func NewOptions(opts ...Option) Options { options := Options{ Logger: logger.DefaultLogger, @@ -45,14 +45,14 @@ func NewOptions(opts ...Option) Options { return options } -// WithNamespace specifies the namespace for the handler +// WithNamespace specifies the namespace for the handler. func WithNamespace(s string) Option { return func(o *Options) { o.Namespace = s } } -// WithRouter specifies a router to be used by the handler +// WithRouter specifies a router to be used by the handler. func WithRouter(r router.Router) Option { return func(o *Options) { o.Router = r @@ -65,14 +65,14 @@ func WithClient(c client.Client) Option { } } -// WithMaxRecvSize specifies max body size +// WithMaxRecvSize specifies max body size. func WithMaxRecvSize(size int64) Option { return func(o *Options) { o.MaxRecvSize = size } } -// WithLogger specifies the logger +// WithLogger specifies the logger. func WithLogger(l logger.Logger) Option { return func(o *Options) { o.Logger = l diff --git a/api/handler/rpc/rpc.go b/api/handler/rpc/rpc.go index ab9e395ac5..99df4f7ee8 100644 --- a/api/handler/rpc/rpc.go +++ b/api/handler/rpc/rpc.go @@ -34,14 +34,14 @@ const ( ) var ( - // supported json codecs + // supported json codecs. jsonCodecs = []string{ "application/grpc+json", "application/json", "application/json-rpc", } - // support proto codecs + // support proto codecs. protoCodecs = []string{ "application/grpc", "application/grpc+proto", @@ -66,7 +66,7 @@ func (b *buffer) Write(_ []byte) (int, error) { return 0, nil } -// strategy is a hack for selection +// strategy is a hack for selection. func strategy(services []*registry.Service) selector.Strategy { return func(_ []*registry.Service) selector.Next { // ignore input to this function, use services above @@ -141,7 +141,7 @@ func (h *rpcHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if isStream(r, service) { // drop older context as it can have timeouts and create new // md, _ := metadata.FromContext(cx) - //serveWebsocket(context.TODO(), w, r, service, c) + // serveWebsocket(context.TODO(), w, r, service, c) if err := serveWebsocket(cx, w, r, service, c); err != nil { logger.Log(log.ErrorLevel, err) } @@ -260,7 +260,7 @@ func hasCodec(ct string, codecs []string) bool { // requestPayload takes a *http.Request. // If the request is a GET the query string parameters are extracted and marshaled to JSON and the raw bytes are returned. -// If the request method is a POST the request body is read and returned +// If the request method is a POST the request body is read and returned. func requestPayload(r *http.Request) ([]byte, error) { var err error @@ -430,7 +430,7 @@ func requestPayload(r *http.Request) ([]byte, error) { if jsonbody != nil { dstmap[ps[0]] = jsonbody } else { - // old unexpected behaviour + // old unexpected behavior dstmap[ps[0]] = bodybuf } } else { @@ -438,7 +438,7 @@ func requestPayload(r *http.Request) ([]byte, error) { if jsonbody != nil { em[ps[len(ps)-1]] = jsonbody } else { - // old unexpected behaviour + // old unexpected behavior em[ps[len(ps)-1]] = bodybuf } for i := len(ps) - 2; i > 0; i-- { @@ -460,7 +460,6 @@ func requestPayload(r *http.Request) ([]byte, error) { //fallback to previous unknown behaviour return bodybuf, nil - } return []byte{}, nil diff --git a/api/handler/rpc/rpc_test.go b/api/handler/rpc/rpc_test.go index d93f5a4dbd..719d7305e6 100644 --- a/api/handler/rpc/rpc_test.go +++ b/api/handler/rpc/rpc_test.go @@ -12,8 +12,7 @@ import ( ) func TestRequestPayloadFromRequest(t *testing.T) { - - // our test event so that we can validate serialising / deserializing of true protos works + // our test event so that we can validate serializing / deserializing of true protos works protoEvent := go_api.Event{ Name: "Test", } @@ -85,7 +84,6 @@ func TestRequestPayloadFromRequest(t *testing.T) { }) t.Run("extracting params from a GET request", func(t *testing.T) { - r, err := http.NewRequest("GET", "http://localhost/my/path", nil) if err != nil { t.Fatalf("Failed to created http.Request: %v", err) @@ -105,7 +103,6 @@ func TestRequestPayloadFromRequest(t *testing.T) { }) t.Run("GET request with no params", func(t *testing.T) { - r, err := http.NewRequest("GET", "http://localhost/my/path", nil) if err != nil { t.Fatalf("Failed to created http.Request: %v", err) diff --git a/api/handler/rpc/stream.go b/api/handler/rpc/stream.go index c3fd675e9c..705057b46e 100644 --- a/api/handler/rpc/stream.go +++ b/api/handler/rpc/stream.go @@ -19,7 +19,7 @@ import ( "go-micro.dev/v4/selector" ) -// serveWebsocket will stream rpc back over websockets assuming json +// serveWebsocket will stream rpc back over websockets assuming json. func serveWebsocket(ctx context.Context, w http.ResponseWriter, r *http.Request, service *router.Route, c client.Client) (err error) { var op ws.OpCode @@ -151,7 +151,7 @@ func serveWebsocket(ctx context.Context, w http.ResponseWriter, r *http.Request, } } -// writeLoop +// writeLoop. func writeLoop(rw io.ReadWriter, stream client.Stream) error { // close stream when done defer stream.Close() diff --git a/api/handler/web/web.go b/api/handler/web/web.go index ca669aba74..68321a7044 100644 --- a/api/handler/web/web.go +++ b/api/handler/web/web.go @@ -50,7 +50,7 @@ func (wh *webHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { httputil.NewSingleHostReverseProxy(rp).ServeHTTP(w, r) } -// getService returns the service for this request from the selector +// getService returns the service for this request from the selector. func (wh *webHandler) getService(r *http.Request) (string, error) { var service *router.Route @@ -78,7 +78,7 @@ func (wh *webHandler) getService(r *http.Request) (string, error) { return fmt.Sprintf("http://%s", s.Address), nil } -// serveWebSocket used to serve a web socket proxied connection +// serveWebSocket used to serve a web socket proxied connection. func (wh *webHandler) serveWebSocket(host string, w http.ResponseWriter, r *http.Request) { req := new(http.Request) *req = *r diff --git a/api/options.go b/api/options.go index c52c918f9b..1af1d52cb6 100644 --- a/api/options.go +++ b/api/options.go @@ -16,7 +16,7 @@ func NewOptions(opts ...Option) Options { return options } -// WithRouter sets the router to use e.g static or registry +// WithRouter sets the router to use e.g static or registry. func WithRouter(r router.Router) Option { return func(o *Options) error { o.Router = r diff --git a/api/resolver/options.go b/api/resolver/options.go index a6fa0ab7f2..9aa1637529 100644 --- a/api/resolver/options.go +++ b/api/resolver/options.go @@ -4,7 +4,6 @@ import ( "net/http" ) -// NewOptions returns new initialised options func NewOptions(opts ...Option) Options { var options Options for _, o := range opts { @@ -18,14 +17,14 @@ func NewOptions(opts ...Option) Options { return options } -// WithHandler sets the handler being used +// WithHandler sets the handler being used. func WithHandler(h string) Option { return func(o *Options) { o.Handler = h } } -// WithNamespace sets the function which determines the namespace for a request +// WithNamespace sets the function which determines the namespace for a request. func WithNamespace(n func(*http.Request) string) Option { return func(o *Options) { o.Namespace = n diff --git a/api/resolver/resolver.go b/api/resolver/resolver.go index 81e8194d1b..5ebe335eb4 100644 --- a/api/resolver/resolver.go +++ b/api/resolver/resolver.go @@ -11,13 +11,13 @@ var ( ErrInvalidPath = errors.New("invalid path") ) -// Resolver resolves requests to endpoints +// Resolver resolves requests to endpoints. type Resolver interface { Resolve(r *http.Request) (*Endpoint, error) String() string } -// Endpoint is the endpoint for a http request +// Endpoint is the endpoint for a http request. type Endpoint struct { // e.g greeter Name string @@ -36,7 +36,7 @@ type Options struct { type Option func(o *Options) -// StaticNamespace returns the same namespace for each request +// StaticNamespace returns the same namespace for each request. func StaticNamespace(ns string) func(*http.Request) string { return func(*http.Request) string { return ns diff --git a/api/resolver/vpath/vpath.go b/api/resolver/vpath/vpath.go index 940e7e4804..ccf3a5cf56 100644 --- a/api/resolver/vpath/vpath.go +++ b/api/resolver/vpath/vpath.go @@ -1,4 +1,4 @@ -// Package vpath resolves using http path and recognised versioned urls +// Package vpath resolves using http path and recognized versioned urls package vpath import ( diff --git a/api/router/endpoint.go b/api/router/endpoint.go index 6ecc702f07..2deff1d737 100644 --- a/api/router/endpoint.go +++ b/api/router/endpoint.go @@ -22,7 +22,7 @@ func slice(s string) []string { return sl } -// Encode encodes an endpoint to endpoint metadata +// Encode encodes an endpoint to endpoint metadata. func Encode(e *Endpoint) map[string]string { if e == nil { return nil @@ -49,7 +49,7 @@ func Encode(e *Endpoint) map[string]string { return ep } -// Decode decodes endpoint metadata into an endpoint +// Decode decodes endpoint metadata into an endpoint. func Decode(e map[string]string) *Endpoint { if e == nil { return nil @@ -65,7 +65,7 @@ func Decode(e map[string]string) *Endpoint { } } -// Validate validates an endpoint to guarantee it won't blow up when being served +// Validate validates an endpoint to guarantee it won't blow up when being served. func Validate(e *Endpoint) error { if e == nil { return errors.New("endpoint is nil") diff --git a/api/router/options.go b/api/router/options.go index 052d288bc9..208cc1ab42 100644 --- a/api/router/options.go +++ b/api/router/options.go @@ -54,7 +54,7 @@ func WithResolver(r resolver.Resolver) Option { } } -// WithLogger sets the underline logger +// WithLogger sets the underline logger. func WithLogger(l logger.Logger) Option { return func(o *Options) { o.Logger = l diff --git a/api/router/registry/registry.go b/api/router/registry/registry.go index eaff03dafc..97b9c28fe2 100644 --- a/api/router/registry/registry.go +++ b/api/router/registry/registry.go @@ -18,14 +18,14 @@ import ( "go-micro.dev/v4/registry/cache" ) -// endpoint struct, that holds compiled pcre +// endpoint struct, that holds compiled pcre. type endpoint struct { hostregs []*regexp.Regexp pathregs []util.Pattern pcreregs []*regexp.Regexp } -// router is the default router +// router is the default router. type registryRouter struct { exit chan bool opts router.Options @@ -48,7 +48,7 @@ func (r *registryRouter) isStopped() bool { } } -// refresh list of api services +// refresh list of api services. func (r *registryRouter) refresh() { var attempts int logger := r.Options().Logger @@ -84,7 +84,7 @@ func (r *registryRouter) refresh() { } } -// process watch event +// process watch event. func (r *registryRouter) process(res *registry.Result) { logger := r.Options().Logger // skip these things @@ -103,7 +103,7 @@ func (r *registryRouter) process(res *registry.Result) { r.store(service) } -// store local endpoint cache +// store local endpoint cache. func (r *registryRouter) store(services []*registry.Service) { logger := r.Options().Logger // endpoints @@ -209,7 +209,7 @@ func (r *registryRouter) store(services []*registry.Service) { } } -// watch for endpoint changes +// watch for endpoint changes. func (r *registryRouter) watch() { var attempts int logger := r.Options().Logger @@ -467,7 +467,7 @@ func newRouter(opts ...router.Option) *registryRouter { return r } -// NewRouter returns the default router +// NewRouter returns the default router. func NewRouter(opts ...router.Option) router.Router { return newRouter(opts...) } diff --git a/api/router/router.go b/api/router/router.go index 780955b645..ed840b8ce4 100644 --- a/api/router/router.go +++ b/api/router/router.go @@ -7,7 +7,7 @@ import ( "go-micro.dev/v4/registry" ) -// Router is used to determine an endpoint for a request +// Router is used to determine an endpoint for a request. type Router interface { // Returns options Options() Options @@ -30,7 +30,7 @@ type Route struct { Versions []*registry.Service } -// Endpoint is a mapping between an RPC method and HTTP endpoint +// Endpoint is a mapping between an RPC method and HTTP endpoint. type Endpoint struct { // RPC Method e.g. Greeter.Hello Name string diff --git a/api/router/static/static.go b/api/router/static/static.go index 2c1c7677f4..cf1f65732e 100644 --- a/api/router/static/static.go +++ b/api/router/static/static.go @@ -23,7 +23,7 @@ type endpoint struct { pcreregs []*regexp.Regexp } -// router is the default router +// router is the default router. type staticRouter struct { exit chan bool opts router.Options @@ -341,7 +341,7 @@ func NewRouter(opts ...router.Option) *staticRouter { opts: options, eps: make(map[string]*endpoint), } - //go r.watch() + // go r.watch() //go r.refresh() return r } diff --git a/api/router/util/parse.go b/api/router/util/parse.go index 1fb6ddafbc..aeb6839457 100644 --- a/api/router/util/parse.go +++ b/api/router/util/parse.go @@ -19,7 +19,7 @@ func (e InvalidTemplateError) Error() string { return fmt.Sprintf("%s: %s", e.msg, e.tmpl) } -// Parse parses the string representation of path template +// Parse parses the string representation of path template. func Parse(tmpl string) (Compiler, error) { if !strings.HasPrefix(tmpl, "/") { return template{}, InvalidTemplateError{tmpl: tmpl, msg: "no leading /"} diff --git a/api/router/util/pattern.go b/api/router/util/pattern.go index 5cc9af1379..b4bb838ca7 100644 --- a/api/router/util/pattern.go +++ b/api/router/util/pattern.go @@ -7,17 +7,17 @@ type OpCode int // These constants are the valid values of OpCode. const ( - // OpNop does nothing + // OpNop does nothing. OpNop = OpCode(iota) - // OpPush pushes a component to stack + // OpPush pushes a component to stack. OpPush - // OpLitPush pushes a component to stack if it matches to the literal + // OpLitPush pushes a component to stack if it matches to the literal. OpLitPush - // OpPushM concatenates the remaining components and pushes it to stack + // OpPushM concatenates the remaining components and pushes it to stack. OpPushM - // OpConcatN pops N items from stack, concatenates them and pushes it back to stack + // OpConcatN pops N items from stack, concatenates them and pushes it back to stack. OpConcatN - // OpCapture pops an item and binds it to the variable + // OpCapture pops an item and binds it to the variable. OpCapture // OpEnd is the least positive invalid opcode. OpEnd diff --git a/api/router/util/runtime.go b/api/router/util/runtime.go index dd97986849..dd76cff0ca 100644 --- a/api/router/util/runtime.go +++ b/api/router/util/runtime.go @@ -49,7 +49,7 @@ type patternOptions struct { // PatternOpt is an option for creating Patterns. type PatternOpt func(*patternOptions) -// Logger sets the logger +// Logger sets the logger. func PatternLogger(l log.Logger) PatternOpt { return func(po *patternOptions) { po.logger = l diff --git a/api/server/acme/acme.go b/api/server/acme/acme.go index c962d0389a..4d726f70ed 100644 --- a/api/server/acme/acme.go +++ b/api/server/acme/acme.go @@ -9,11 +9,11 @@ import ( var ( // ErrProviderNotImplemented can be returned when attempting to - // instantiate an unimplemented provider + // instantiate an unimplemented provider. ErrProviderNotImplemented = errors.New("Provider not implemented") ) -// Provider is a ACME provider interface +// Provider is a ACME provider interface. type Provider interface { // Listen returns a new listener Listen(...string) (net.Listener, error) @@ -21,7 +21,7 @@ type Provider interface { TLSConfig(...string) (*tls.Config, error) } -// The Let's Encrypt ACME endpoints +// The Let's Encrypt ACME endpoints. const ( LetsEncryptStagingCA = "https://acme-staging-v02.api.letsencrypt.org/directory" LetsEncryptProductionCA = "https://acme-v02.api.letsencrypt.org/directory" diff --git a/api/server/acme/autocert/autocert.go b/api/server/acme/autocert/autocert.go index b1bf694c0d..e6dac900a5 100644 --- a/api/server/acme/autocert/autocert.go +++ b/api/server/acme/autocert/autocert.go @@ -13,17 +13,17 @@ import ( log "go-micro.dev/v4/logger" ) -// autoCertACME is the ACME provider from golang.org/x/crypto/acme/autocert +// autoCertACME is the ACME provider from golang.org/x/crypto/acme/autocert. type autocertProvider struct { logger log.Logger } -// Listen implements acme.Provider +// Listen implements acme.Provider. func (a *autocertProvider) Listen(hosts ...string) (net.Listener, error) { return autocert.NewListener(hosts...), nil } -// TLSConfig returns a new tls config +// TLSConfig returns a new tls config. func (a *autocertProvider) TLSConfig(hosts ...string) (*tls.Config, error) { logger := log.LoggerOrDefault(a.logger) // create a new manager @@ -42,7 +42,7 @@ func (a *autocertProvider) TLSConfig(hosts ...string) (*tls.Config, error) { return m.TLSConfig(), nil } -// New returns an autocert acme.Provider +// New returns an autocert acme.Provider. func NewProvider() acme.Provider { return &autocertProvider{} } diff --git a/api/server/acme/options.go b/api/server/acme/options.go index d6ad845cdc..12054fa3c7 100644 --- a/api/server/acme/options.go +++ b/api/server/acme/options.go @@ -6,10 +6,10 @@ import ( "go-micro.dev/v4/logger" ) -// Option (or Options) are passed to New() to configure providers +// Option (or Options) are passed to New() to configure providers. type Option func(o *Options) -// Options represents various options you can present to ACME providers +// Options represents various options you can present to ACME providers. type Options struct { // AcceptTLS must be set to true to indicate that you have read your // provider's terms of service. @@ -31,14 +31,14 @@ type Options struct { Logger logger.Logger } -// AcceptToS indicates whether you accept your CA's terms of service +// AcceptToS indicates whether you accept your CA's terms of service. func AcceptToS(b bool) Option { return func(o *Options) { o.AcceptToS = b } } -// CA sets the CA of an acme.Options +// CA sets the CA of an acme.Options. func CA(CA string) Option { return func(o *Options) { o.CA = CA @@ -63,14 +63,14 @@ func OnDemand(b bool) Option { // Cache provides a cache / storage interface to the underlying ACME library // as there is no standard, this needs to be validated by the underlying -// implentation. +// implementation. func Cache(c interface{}) Option { return func(o *Options) { o.Cache = c } } -// Logger sets the underline logger +// Logger sets the underline logger. func Logger(l logger.Logger) Option { return func(o *Options) { o.Logger = l diff --git a/api/server/cors/cors.go b/api/server/cors/cors.go index d1041a3d1a..c4cd4db4ed 100644 --- a/api/server/cors/cors.go +++ b/api/server/cors/cors.go @@ -11,7 +11,7 @@ type Config struct { AllowHeaders string } -// CombinedCORSHandler wraps a server and provides CORS headers +// CombinedCORSHandler wraps a server and provides CORS headers. func CombinedCORSHandler(h http.Handler, config *Config) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if config != nil { @@ -25,7 +25,7 @@ func CombinedCORSHandler(h http.Handler, config *Config) http.Handler { }) } -// SetHeaders sets the CORS headers +// SetHeaders sets the CORS headers. func SetHeaders(w http.ResponseWriter, _ *http.Request, config *Config) { set := func(w http.ResponseWriter, k, v string) { if v := w.Header().Get(k); len(v) > 0 { @@ -33,7 +33,7 @@ func SetHeaders(w http.ResponseWriter, _ *http.Request, config *Config) { } w.Header().Set(k, v) } - //For forward-compatible code, default values may not be provided in the future + // For forward-compatible code, default values may not be provided in the future if config.AllowCredentials { set(w, "Access-Control-Allow-Credentials", "true") } else { diff --git a/api/server/http/http.go b/api/server/http/http.go index a6356e6164..cfe0ca92a4 100644 --- a/api/server/http/http.go +++ b/api/server/http/http.go @@ -94,7 +94,7 @@ func (s *httpServer) Start() error { go func() { if err := http.Serve(l, s.mux); err != nil { // temporary fix - //logger.Log(log.FatalLevel, err) + // logger.Log(log.FatalLevel, err) logger.Log(log.ErrorLevel, err) } }() diff --git a/api/server/http/http_test.go b/api/server/http/http_test.go index 9106f17d99..b1ddab8322 100644 --- a/api/server/http/http_test.go +++ b/api/server/http/http_test.go @@ -2,11 +2,12 @@ package http import ( "fmt" - "go-micro.dev/v4/api/server" - "go-micro.dev/v4/api/server/cors" "io" "net/http" "testing" + + "go-micro.dev/v4/api/server" + "go-micro.dev/v4/api/server/cors" ) func TestHTTPServer(t *testing.T) { diff --git a/api/server/options.go b/api/server/options.go index acaf7b6752..8ddc13c2f2 100644 --- a/api/server/options.go +++ b/api/server/options.go @@ -94,7 +94,7 @@ func Resolver(r resolver.Resolver) Option { } } -// Logger sets the underline logging framework +// Logger sets the underline logging framework. func Logger(l logger.Logger) Option { return func(o *Options) { o.Logger = l diff --git a/api/server/server.go b/api/server/server.go index b1d63e3549..be6e40f179 100644 --- a/api/server/server.go +++ b/api/server/server.go @@ -5,7 +5,7 @@ import ( "net/http" ) -// Server serves api requests +// Server serves api requests. type Server interface { Address() string Init(opts ...Option) error diff --git a/auth/auth.go b/auth/auth.go index a2c601a0a1..99140102d0 100644 --- a/auth/auth.go +++ b/auth/auth.go @@ -8,22 +8,22 @@ import ( ) const ( - // BearerScheme used for Authorization header + // BearerScheme used for Authorization header. BearerScheme = "Bearer " - // ScopePublic is the scope applied to a rule to allow access to the public + // ScopePublic is the scope applied to a rule to allow access to the public. ScopePublic = "" - // ScopeAccount is the scope applied to a rule to limit to users with any valid account + // ScopeAccount is the scope applied to a rule to limit to users with any valid account. ScopeAccount = "*" ) var ( - // ErrInvalidToken is when the token provided is not valid + // ErrInvalidToken is when the token provided is not valid. ErrInvalidToken = errors.New("invalid token provided") - // ErrForbidden is when a user does not have the necessary scope to access a resource + // ErrForbidden is when a user does not have the necessary scope to access a resource. ErrForbidden = errors.New("resource forbidden") ) -// Auth provides authentication and authorization +// Auth provides authentication and authorization. type Auth interface { // Init the auth Init(opts ...Option) @@ -39,7 +39,7 @@ type Auth interface { String() string } -// Rules manages access to resources +// Rules manages access to resources. type Rules interface { // Verify an account has access to a resource using the rules Verify(acc *Account, res *Resource, opts ...VerifyOption) error @@ -51,7 +51,7 @@ type Rules interface { List(...ListOption) ([]*Rule, error) } -// Account provided by an auth provider +// Account provided by an auth provider. type Account struct { // ID of the account e.g. email ID string `json:"id"` @@ -67,7 +67,7 @@ type Account struct { Secret string `json:"secret"` } -// Token can be short or long lived +// Token can be short or long lived. type Token struct { // The token to be used for accessing resources AccessToken string `json:"access_token"` @@ -79,12 +79,12 @@ type Token struct { Expiry time.Time `json:"expiry"` } -// Expired returns a boolean indicating if the token needs to be refreshed +// Expired returns a boolean indicating if the token needs to be refreshed. func (t *Token) Expired() bool { return t.Expiry.Unix() < time.Now().Unix() } -// Resource is an entity such as a user or +// Resource is an entity such as a user or. type Resource struct { // Name of the resource, e.g. go.micro.service.notes Name string `json:"name"` @@ -94,17 +94,17 @@ type Resource struct { Endpoint string `json:"endpoint"` } -// Access defines the type of access a rule grants +// Access defines the type of access a rule grants. type Access int const ( - // AccessGranted to a resource + // AccessGranted to a resource. AccessGranted Access = iota - // AccessDenied to a resource + // AccessDenied to a resource. AccessDenied ) -// Rule is used to verify access to a resource +// Rule is used to verify access to a resource. type Rule struct { // ID of the rule, e.g. "public" ID string @@ -125,13 +125,13 @@ type accountKey struct{} // AccountFromContext gets the account from the context, which // is set by the auth wrapper at the start of a call. If the account // is not set, a nil account will be returned. The error is only returned -// when there was a problem retrieving an account +// when there was a problem retrieving an account. func AccountFromContext(ctx context.Context) (*Account, bool) { acc, ok := ctx.Value(accountKey{}).(*Account) return acc, ok } -// ContextWithAccount sets the account in the context +// ContextWithAccount sets the account in the context. func ContextWithAccount(ctx context.Context, account *Account) context.Context { return context.WithValue(ctx, accountKey{}, account) } diff --git a/auth/noop.go b/auth/noop.go index 2c683c2625..682e8f3fe4 100644 --- a/auth/noop.go +++ b/auth/noop.go @@ -30,24 +30,24 @@ type noop struct { type noopRules struct{} -// String returns the name of the implementation +// String returns the name of the implementation. func (n *noop) String() string { return "noop" } -// Init the auth +// Init the auth. func (n *noop) Init(opts ...Option) { for _, o := range opts { o(&n.opts) } } -// Options set for auth +// Options set for auth. func (n *noop) Options() Options { return n.opts } -// Generate a new account +// Generate a new account. func (n *noop) Generate(id string, opts ...GenerateOption) (*Account, error) { options := NewGenerateOptions(opts...) @@ -60,18 +60,18 @@ func (n *noop) Generate(id string, opts ...GenerateOption) (*Account, error) { }, nil } -// Grant access to a resource +// Grant access to a resource. func (n *noopRules) Grant(rule *Rule) error { return nil } -// Revoke access to a resource +// Revoke access to a resource. func (n *noopRules) Revoke(rule *Rule) error { return nil } // Rules used to verify requests -// Verify an account has access to a resource +// Verify an account has access to a resource. func (n *noopRules) Verify(acc *Account, res *Resource, opts ...VerifyOption) error { return nil } @@ -80,12 +80,12 @@ func (n *noopRules) List(opts ...ListOption) ([]*Rule, error) { return []*Rule{}, nil } -// Inspect a token +// Inspect a token. func (n *noop) Inspect(token string) (*Account, error) { return &Account{ID: uuid.New().String(), Issuer: n.Options().Namespace}, nil } -// Token generation using an account id and secret +// Token generation using an account id and secret. func (n *noop) Token(opts ...TokenOption) (*Token, error) { return &Token{}, nil } diff --git a/auth/options.go b/auth/options.go index 6b4c16e857..82e27c811d 100644 --- a/auth/options.go +++ b/auth/options.go @@ -40,42 +40,42 @@ type Options struct { type Option func(o *Options) -// Addrs is the auth addresses to use +// Addrs is the auth addresses to use. func Addrs(addrs ...string) Option { return func(o *Options) { o.Addrs = addrs } } -// Namespace the service belongs to +// Namespace the service belongs to. func Namespace(n string) Option { return func(o *Options) { o.Namespace = n } } -// PublicKey is the JWT public key +// PublicKey is the JWT public key. func PublicKey(key string) Option { return func(o *Options) { o.PublicKey = key } } -// PrivateKey is the JWT private key +// PrivateKey is the JWT private key. func PrivateKey(key string) Option { return func(o *Options) { o.PrivateKey = key } } -// WithLogger sets the underline logger +// WithLogger sets the underline logger. func WithLogger(l logger.Logger) Option { return func(o *Options) { o.Logger = l } } -// Credentials sets the auth credentials +// Credentials sets the auth credentials. func Credentials(id, secret string) Option { return func(o *Options) { o.ID = id @@ -83,7 +83,7 @@ func Credentials(id, secret string) Option { } } -// ClientToken sets the auth token to use when making requests +// ClientToken sets the auth token to use when making requests. func ClientToken(token *Token) Option { return func(o *Options) { o.Token = token @@ -105,42 +105,42 @@ type GenerateOptions struct { type GenerateOption func(o *GenerateOptions) -// WithSecret for the generated account +// WithSecret for the generated account. func WithSecret(s string) GenerateOption { return func(o *GenerateOptions) { o.Secret = s } } -// WithType for the generated account +// WithType for the generated account. func WithType(t string) GenerateOption { return func(o *GenerateOptions) { o.Type = t } } -// WithMetadata for the generated account +// WithMetadata for the generated account. func WithMetadata(md map[string]string) GenerateOption { return func(o *GenerateOptions) { o.Metadata = md } } -// WithProvider for the generated account +// WithProvider for the generated account. func WithProvider(p string) GenerateOption { return func(o *GenerateOptions) { o.Provider = p } } -// WithScopes for the generated account +// WithScopes for the generated account. func WithScopes(s ...string) GenerateOption { return func(o *GenerateOptions) { o.Scopes = s } } -// NewGenerateOptions from a slice of options +// NewGenerateOptions from a slice of options. func NewGenerateOptions(opts ...GenerateOption) GenerateOptions { var options GenerateOptions for _, o := range opts { @@ -162,7 +162,7 @@ type TokenOptions struct { type TokenOption func(o *TokenOptions) -// WithExpiry for the token +// WithExpiry for the token. func WithExpiry(ex time.Duration) TokenOption { return func(o *TokenOptions) { o.Expiry = ex @@ -182,14 +182,14 @@ func WithToken(rt string) TokenOption { } } -// NewTokenOptions from a slice of options +// NewTokenOptions from a slice of options. func NewTokenOptions(opts ...TokenOption) TokenOptions { var options TokenOptions for _, o := range opts { o(&options) } - // set defualt expiry of token + // set default expiry of token if options.Expiry == 0 { options.Expiry = time.Minute } diff --git a/auth/rules.go b/auth/rules.go index 33f3f45ad0..78fa0fa073 100644 --- a/auth/rules.go +++ b/auth/rules.go @@ -8,7 +8,7 @@ import ( // Verify an account has access to a resource using the rules provided. If the account does not have // access an error will be returned. If there are no rules provided which match the resource, an error -// will be returned +// will be returned. func Verify(rules []*Rule, acc *Account, res *Resource) error { // the rule is only to be applied if the type matches the resource or is catch-all (*) validTypes := []string{"*", res.Type} diff --git a/auth/rules_test.go b/auth/rules_test.go index 2c821df741..58f858accd 100644 --- a/auth/rules_test.go +++ b/auth/rules_test.go @@ -42,7 +42,7 @@ func TestVerify(t *testing.T) { Account: &Account{}, Resource: srvResource, Rules: []*Rule{ - &Rule{ + { Scope: "", Resource: catchallResource, }, @@ -52,7 +52,7 @@ func TestVerify(t *testing.T) { Name: "CatchallPublicNoAccount", Resource: srvResource, Rules: []*Rule{ - &Rule{ + { Scope: "", Resource: catchallResource, }, @@ -63,7 +63,7 @@ func TestVerify(t *testing.T) { Account: &Account{}, Resource: srvResource, Rules: []*Rule{ - &Rule{ + { Scope: "*", Resource: catchallResource, }, @@ -73,7 +73,7 @@ func TestVerify(t *testing.T) { Name: "CatchallPrivateNoAccount", Resource: srvResource, Rules: []*Rule{ - &Rule{ + { Scope: "*", Resource: catchallResource, }, @@ -85,7 +85,7 @@ func TestVerify(t *testing.T) { Resource: srvResource, Account: &Account{}, Rules: []*Rule{ - &Rule{ + { Scope: "*", Resource: &Resource{ Type: srvResource.Type, @@ -100,7 +100,7 @@ func TestVerify(t *testing.T) { Resource: srvResource, Account: &Account{}, Rules: []*Rule{ - &Rule{ + { Scope: "*", Resource: &Resource{ Type: srvResource.Type, @@ -118,7 +118,7 @@ func TestVerify(t *testing.T) { Scopes: []string{"neededscope"}, }, Rules: []*Rule{ - &Rule{ + { Scope: "neededscope", Resource: srvResource, }, @@ -131,7 +131,7 @@ func TestVerify(t *testing.T) { Scopes: []string{"neededscope"}, }, Rules: []*Rule{ - &Rule{ + { Scope: "invalidscope", Resource: srvResource, }, @@ -143,7 +143,7 @@ func TestVerify(t *testing.T) { Resource: srvResource, Account: &Account{}, Rules: []*Rule{ - &Rule{ + { Scope: "*", Resource: catchallResource, Access: AccessDenied, @@ -156,7 +156,7 @@ func TestVerify(t *testing.T) { Resource: srvResource, Account: &Account{}, Rules: []*Rule{ - &Rule{ + { Scope: "*", Resource: catchallResource, Access: AccessDenied, @@ -169,13 +169,13 @@ func TestVerify(t *testing.T) { Resource: srvResource, Account: &Account{}, Rules: []*Rule{ - &Rule{ + { Scope: "*", Resource: catchallResource, Access: AccessGranted, Priority: 1, }, - &Rule{ + { Scope: "*", Resource: catchallResource, Access: AccessDenied, @@ -188,13 +188,13 @@ func TestVerify(t *testing.T) { Resource: srvResource, Account: &Account{}, Rules: []*Rule{ - &Rule{ + { Scope: "*", Resource: catchallResource, Access: AccessGranted, Priority: 0, }, - &Rule{ + { Scope: "*", Resource: catchallResource, Access: AccessDenied, @@ -208,7 +208,7 @@ func TestVerify(t *testing.T) { Resource: webResource, Account: &Account{}, Rules: []*Rule{ - &Rule{ + { Scope: "*", Resource: webResource, }, @@ -219,7 +219,7 @@ func TestVerify(t *testing.T) { Resource: webResource, Account: &Account{}, Rules: []*Rule{ - &Rule{ + { Scope: "*", Resource: &Resource{ Type: webResource.Type, @@ -235,7 +235,7 @@ func TestVerify(t *testing.T) { Resource: webResource, Account: &Account{}, Rules: []*Rule{ - &Rule{ + { Scope: "*", Resource: &Resource{ Type: webResource.Type, @@ -250,7 +250,7 @@ func TestVerify(t *testing.T) { Resource: webResource, Account: &Account{}, Rules: []*Rule{ - &Rule{ + { Scope: "*", Resource: &Resource{ Type: webResource.Type, @@ -265,7 +265,7 @@ func TestVerify(t *testing.T) { Resource: webResource, Account: &Account{}, Rules: []*Rule{ - &Rule{ + { Scope: "*", Resource: &Resource{ Type: webResource.Type, diff --git a/broker/broker.go b/broker/broker.go index b1ce35bd95..3dae717b47 100644 --- a/broker/broker.go +++ b/broker/broker.go @@ -23,7 +23,7 @@ type Message struct { Body []byte } -// Event is given to a subscription handler for processing +// Event is given to a subscription handler for processing. type Event interface { Topic() string Message() *Message @@ -31,7 +31,7 @@ type Event interface { Error() error } -// Subscriber is a convenience return type for the Subscribe method +// Subscriber is a convenience return type for the Subscribe method. type Subscriber interface { Options() SubscribeOptions Topic() string diff --git a/broker/http.go b/broker/http.go index e145f05895..442e25833c 100644 --- a/broker/http.go +++ b/broker/http.go @@ -27,7 +27,7 @@ import ( mls "go-micro.dev/v4/util/tls" ) -// HTTP Broker is a point to point async broker +// HTTP Broker is a point to point async broker. type httpBroker struct { id string address string @@ -315,7 +315,7 @@ func (h *httpBroker) ServeHTTP(w http.ResponseWriter, req *http.Request) { } topic := m.Header["Micro-Topic"] - //delete(m.Header, ":topic") + // delete(m.Header, ":topic") if len(topic) == 0 { errr := merr.InternalServerError("go.micro.broker", "Topic not found") @@ -703,7 +703,7 @@ func (h *httpBroker) String() string { return "http" } -// NewBroker returns a new http broker +// NewBroker returns a new http broker. func NewBroker(opts ...Option) Broker { return newHttpBroker(opts...) } diff --git a/broker/http_test.go b/broker/http_test.go index 3a0d87a8d1..a9a676ab8a 100644 --- a/broker/http_test.go +++ b/broker/http_test.go @@ -11,7 +11,7 @@ import ( ) var ( - // mock data + // mock data. testData = map[string][]*registry.Service{ "foo": { { diff --git a/broker/options.go b/broker/options.go index f0d7e5bbfe..32cec6f4c9 100644 --- a/broker/options.go +++ b/broker/options.go @@ -53,7 +53,7 @@ type Option func(*Options) type PublishOption func(*PublishOptions) -// PublishContext set context +// PublishContext set context. func PublishContext(ctx context.Context) PublishOption { return func(o *PublishOptions) { o.Context = ctx @@ -87,7 +87,7 @@ func NewSubscribeOptions(opts ...SubscribeOption) SubscribeOptions { return opt } -// Addrs sets the host addresses to be used by the broker +// Addrs sets the host addresses to be used by the broker. func Addrs(addrs ...string) Option { return func(o *Options) { o.Addrs = addrs @@ -95,7 +95,7 @@ func Addrs(addrs ...string) Option { } // Codec sets the codec used for encoding/decoding used where -// a broker does not support headers +// a broker does not support headers. func Codec(c codec.Marshaler) Option { return func(o *Options) { o.Codec = c @@ -111,14 +111,14 @@ func DisableAutoAck() SubscribeOption { } // ErrorHandler will catch all broker errors that cant be handled -// in normal way, for example Codec errors +// in normal way, for example Codec errors. func ErrorHandler(h Handler) Option { return func(o *Options) { o.ErrorHandler = h } } -// Queue sets the name of the queue to share messages on +// Queue sets the name of the queue to share messages on. func Queue(name string) SubscribeOption { return func(o *SubscribeOptions) { o.Queue = name @@ -131,28 +131,28 @@ func Registry(r registry.Registry) Option { } } -// Secure communication with the broker +// Secure communication with the broker. func Secure(b bool) Option { return func(o *Options) { o.Secure = b } } -// Specify TLS Config +// Specify TLS Config. func TLSConfig(t *tls.Config) Option { return func(o *Options) { o.TLSConfig = t } } -// Logger sets the underline logger +// Logger sets the underline logger. func Logger(l logger.Logger) Option { return func(o *Options) { o.Logger = l } } -// SubscribeContext set context +// SubscribeContext set context. func SubscribeContext(ctx context.Context) SubscribeOption { return func(o *SubscribeOptions) { o.Context = ctx diff --git a/cache/options.go b/cache/options.go index 56a1d5028b..41ad71689a 100644 --- a/cache/options.go +++ b/cache/options.go @@ -36,21 +36,21 @@ func Items(i map[string]Item) Option { } } -// WithAddress sets the cache service address or connection information +// WithAddress sets the cache service address or connection information. func WithAddress(addr string) Option { return func(o *Options) { o.Address = addr } } -// WithContext sets the cache context, for any extra configuration +// WithContext sets the cache context, for any extra configuration. func WithContext(c context.Context) Option { return func(o *Options) { o.Context = c } } -// WithLogger sets underline logger +// WithLogger sets underline logger. func WithLogger(l logger.Logger) Option { return func(o *Options) { o.Logger = l diff --git a/client/cache.go b/client/cache.go index 8667c6d05e..3509f8822f 100644 --- a/client/cache.go +++ b/client/cache.go @@ -11,29 +11,29 @@ import ( "go-micro.dev/v4/metadata" ) -// NewCache returns an initialised cache. +// NewCache returns an initialized cache. func NewCache() *Cache { return &Cache{ cache: cache.New(cache.NoExpiration, 30*time.Second), } } -// Cache for responses +// Cache for responses. type Cache struct { cache *cache.Cache } -// Get a response from the cache +// Get a response from the cache. func (c *Cache) Get(ctx context.Context, req *Request) (interface{}, bool) { return c.cache.Get(key(ctx, req)) } -// Set a response in the cache +// Set a response in the cache. func (c *Cache) Set(ctx context.Context, req *Request, rsp interface{}, expiry time.Duration) { c.cache.Set(key(ctx, req), rsp, expiry) } -// List the key value pairs in the cache +// List the key value pairs in the cache. func (c *Cache) List() map[string]string { items := c.cache.Items() @@ -46,7 +46,7 @@ func (c *Cache) List() map[string]string { return rsp } -// key returns a hash for the context and request +// key returns a hash for the context and request. func key(ctx context.Context, req *Request) string { ns, _ := metadata.Get(ctx, "Micro-Namespace") diff --git a/client/client.go b/client/client.go index fadd5412ea..8c05435e14 100644 --- a/client/client.go +++ b/client/client.go @@ -22,19 +22,19 @@ type Client interface { String() string } -// Router manages request routing +// Router manages request routing. type Router interface { SendRequest(context.Context, Request) (Response, error) } -// Message is the interface for publishing asynchronously +// Message is the interface for publishing asynchronously. type Message interface { Topic() string Payload() interface{} ContentType() string } -// Request is the interface for a synchronous request used by Call or Stream +// Request is the interface for a synchronous request used by Call or Stream. type Request interface { // The service to call Service() string @@ -52,7 +52,7 @@ type Request interface { Stream() bool } -// Response is the response received from a service +// Response is the response received from a service. type Response interface { // Read the response Codec() codec.Reader @@ -62,7 +62,7 @@ type Response interface { Read() ([]byte, error) } -// Stream is the inteface for a bidirectional synchronous stream +// Stream is the inteface for a bidirectional synchronous stream. type Stream interface { Closer // Context for the stream @@ -81,48 +81,48 @@ type Stream interface { Close() error } -// Closer handle client close +// Closer handle client close. type Closer interface { // CloseSend closes the send direction of the stream. CloseSend() error } -// Option used by the Client +// Option used by the Client. type Option func(*Options) -// CallOption used by Call or Stream +// CallOption used by Call or Stream. type CallOption func(*CallOptions) -// PublishOption used by Publish +// PublishOption used by Publish. type PublishOption func(*PublishOptions) -// MessageOption used by NewMessage +// MessageOption used by NewMessage. type MessageOption func(*MessageOptions) -// RequestOption used by NewRequest +// RequestOption used by NewRequest. type RequestOption func(*RequestOptions) var ( - // DefaultClient is a default client to use out of the box + // DefaultClient is a default client to use out of the box. DefaultClient Client = newRpcClient() - // DefaultBackoff is the default backoff function for retries + // DefaultBackoff is the default backoff function for retries. DefaultBackoff = exponentialBackoff - // DefaultRetry is the default check-for-retry function for retries + // DefaultRetry is the default check-for-retry function for retries. DefaultRetry = RetryOnError - // DefaultRetries is the default number of times a request is tried + // DefaultRetries is the default number of times a request is tried. DefaultRetries = 1 - // DefaultRequestTimeout is the default request timeout + // DefaultRequestTimeout is the default request timeout. DefaultRequestTimeout = time.Second * 5 - // DefaultPoolSize sets the connection pool size + // DefaultPoolSize sets the connection pool size. DefaultPoolSize = 100 - // DefaultPoolTTL sets the connection pool ttl + // DefaultPoolTTL sets the connection pool ttl. DefaultPoolTTL = time.Minute - // NewClient returns a new client + // NewClient returns a new client. NewClient func(...Option) Client = newRpcClient ) -// Makes a synchronous call to a service using the default client +// Makes a synchronous call to a service using the default client. func Call(ctx context.Context, request Request, response interface{}, opts ...CallOption) error { return DefaultClient.Call(ctx, request, response, opts...) } @@ -133,13 +133,13 @@ func Publish(ctx context.Context, msg Message, opts ...PublishOption) error { return DefaultClient.Publish(ctx, msg, opts...) } -// Creates a new message using the default client +// Creates a new message using the default client. func NewMessage(topic string, payload interface{}, opts ...MessageOption) Message { return DefaultClient.NewMessage(topic, payload, opts...) } // Creates a new request using the default client. Content Type will -// be set to the default within options and use the appropriate codec +// be set to the default within options and use the appropriate codec. func NewRequest(service, endpoint string, request interface{}, reqOpts ...RequestOption) Request { return DefaultClient.NewRequest(service, endpoint, request, reqOpts...) } diff --git a/client/common_test.go b/client/common_test.go index e33b3c3940..f03b137ec3 100644 --- a/client/common_test.go +++ b/client/common_test.go @@ -5,7 +5,7 @@ import ( ) var ( - // mock data + // mock data. testData = map[string][]*registry.Service{ "foo": { { diff --git a/client/options.go b/client/options.go index 98c3fa4936..074c00de4e 100644 --- a/client/options.go +++ b/client/options.go @@ -127,42 +127,42 @@ func NewOptions(options ...Option) Options { return opts } -// Broker to be used for pub/sub +// Broker to be used for pub/sub. func Broker(b broker.Broker) Option { return func(o *Options) { o.Broker = b } } -// Codec to be used to encode/decode requests for a given content type +// Codec to be used to encode/decode requests for a given content type. func Codec(contentType string, c codec.NewCodec) Option { return func(o *Options) { o.Codecs[contentType] = c } } -// Default content type of the client +// Default content type of the client. func ContentType(ct string) Option { return func(o *Options) { o.ContentType = ct } } -// PoolSize sets the connection pool size +// PoolSize sets the connection pool size. func PoolSize(d int) Option { return func(o *Options) { o.PoolSize = d } } -// PoolTTL sets the connection pool ttl +// PoolTTL sets the connection pool ttl. func PoolTTL(d time.Duration) Option { return func(o *Options) { o.PoolTTL = d } } -// Registry to find nodes for a given service +// Registry to find nodes for a given service. func Registry(r registry.Registry) Option { return func(o *Options) { o.Registry = r @@ -171,28 +171,28 @@ func Registry(r registry.Registry) Option { } } -// Transport to use for communication e.g http, rabbitmq, etc +// Transport to use for communication e.g http, rabbitmq, etc. func Transport(t transport.Transport) Option { return func(o *Options) { o.Transport = t } } -// Select is used to select a node to route a request to +// Select is used to select a node to route a request to. func Selector(s selector.Selector) Option { return func(o *Options) { o.Selector = s } } -// Adds a Wrapper to a list of options passed into the client +// Adds a Wrapper to a list of options passed into the client. func Wrap(w Wrapper) Option { return func(o *Options) { o.Wrappers = append(o.Wrappers, w) } } -// Adds a Wrapper to the list of CallFunc wrappers +// Adds a Wrapper to the list of CallFunc wrappers. func WrapCall(cw ...CallWrapper) Option { return func(o *Options) { o.CallOptions.CallWrappers = append(o.CallOptions.CallWrappers, cw...) @@ -200,7 +200,7 @@ func WrapCall(cw ...CallWrapper) Option { } // Backoff is used to set the backoff function used -// when retrying Calls +// when retrying Calls. func Backoff(fn BackoffFunc) Option { return func(o *Options) { o.CallOptions.Backoff = fn @@ -230,14 +230,14 @@ func RequestTimeout(d time.Duration) Option { } } -// StreamTimeout sets the stream timeout +// StreamTimeout sets the stream timeout. func StreamTimeout(d time.Duration) Option { return func(o *Options) { o.CallOptions.StreamTimeout = d } } -// Transport dial timeout +// Transport dial timeout. func DialTimeout(d time.Duration) Option { return func(o *Options) { o.CallOptions.DialTimeout = d @@ -246,21 +246,21 @@ func DialTimeout(d time.Duration) Option { // Call Options -// WithExchange sets the exchange to route a message through +// WithExchange sets the exchange to route a message through. func WithExchange(e string) PublishOption { return func(o *PublishOptions) { o.Exchange = e } } -// PublishContext sets the context in publish options +// PublishContext sets the context in publish options. func PublishContext(ctx context.Context) PublishOption { return func(o *PublishOptions) { o.Context = ctx } } -// WithAddress sets the remote addresses to use rather than using service discovery +// WithAddress sets the remote addresses to use rather than using service discovery. func WithAddress(a ...string) CallOption { return func(o *CallOptions) { o.Address = a @@ -273,7 +273,7 @@ func WithSelectOption(so ...selector.SelectOption) CallOption { } } -// WithCallWrapper is a CallOption which adds to the existing CallFunc wrappers +// WithCallWrapper is a CallOption which adds to the existing CallFunc wrappers. func WithCallWrapper(cw ...CallWrapper) CallOption { return func(o *CallOptions) { o.CallWrappers = append(o.CallWrappers, cw...) @@ -281,7 +281,7 @@ func WithCallWrapper(cw ...CallWrapper) CallOption { } // WithBackoff is a CallOption which overrides that which -// set in Options.CallOptions +// set in Options.CallOptions. func WithBackoff(fn BackoffFunc) CallOption { return func(o *CallOptions) { o.Backoff = fn @@ -289,7 +289,7 @@ func WithBackoff(fn BackoffFunc) CallOption { } // WithRetry is a CallOption which overrides that which -// set in Options.CallOptions +// set in Options.CallOptions. func WithRetry(fn RetryFunc) CallOption { return func(o *CallOptions) { o.Retry = fn @@ -297,7 +297,7 @@ func WithRetry(fn RetryFunc) CallOption { } // WithRetries is a CallOption which overrides that which -// set in Options.CallOptions +// set in Options.CallOptions. func WithRetries(i int) CallOption { return func(o *CallOptions) { o.Retries = i @@ -305,14 +305,14 @@ func WithRetries(i int) CallOption { } // WithRequestTimeout is a CallOption which overrides that which -// set in Options.CallOptions +// set in Options.CallOptions. func WithRequestTimeout(d time.Duration) CallOption { return func(o *CallOptions) { o.RequestTimeout = d } } -// WithStreamTimeout sets the stream timeout +// WithStreamTimeout sets the stream timeout. func WithStreamTimeout(d time.Duration) CallOption { return func(o *CallOptions) { o.StreamTimeout = d @@ -320,7 +320,7 @@ func WithStreamTimeout(d time.Duration) CallOption { } // WithDialTimeout is a CallOption which overrides that which -// set in Options.CallOptions +// set in Options.CallOptions. func WithDialTimeout(d time.Duration) CallOption { return func(o *CallOptions) { o.DialTimeout = d @@ -328,7 +328,7 @@ func WithDialTimeout(d time.Duration) CallOption { } // WithServiceToken is a CallOption which overrides the -// authorization header with the services own auth token +// authorization header with the services own auth token. func WithServiceToken() CallOption { return func(o *CallOptions) { o.ServiceToken = true @@ -336,7 +336,7 @@ func WithServiceToken() CallOption { } // WithCache is a CallOption which sets the duration the response -// shoull be cached for +// shoull be cached for. func WithCache(c time.Duration) CallOption { return func(o *CallOptions) { o.CacheExpiry = c @@ -363,14 +363,14 @@ func StreamingRequest() RequestOption { } } -// WithRouter sets the client router +// WithRouter sets the client router. func WithRouter(r Router) Option { return func(o *Options) { o.Router = r } } -// WithLogger sets the underline logger +// WithLogger sets the underline logger. func WithLogger(l logger.Logger) Option { return func(o *Options) { o.Logger = l diff --git a/client/options_test.go b/client/options_test.go index d4e6733717..a872792bed 100644 --- a/client/options_test.go +++ b/client/options_test.go @@ -78,8 +78,6 @@ func TestCallOptions(t *testing.T) { if e := o.CallOptions.DialTimeout * (time.Second * 10); callOpts.DialTimeout != e { t.Fatalf("Expected %v got %v", e, callOpts.DialTimeout) } - } - } } diff --git a/client/retry.go b/client/retry.go index c05ffb86ea..e981cd4c63 100644 --- a/client/retry.go +++ b/client/retry.go @@ -6,15 +6,15 @@ import ( "go-micro.dev/v4/errors" ) -// note that returning either false or a non-nil error will result in the call not being retried +// note that returning either false or a non-nil error will result in the call not being retried. type RetryFunc func(ctx context.Context, req Request, retryCount int, err error) (bool, error) -// RetryAlways always retry on error +// RetryAlways always retry on error. func RetryAlways(ctx context.Context, req Request, retryCount int, err error) (bool, error) { return true, nil } -// RetryOnError retries a request on a 500 or timeout error +// RetryOnError retries a request on a 500 or timeout error. func RetryOnError(ctx context.Context, req Request, retryCount int, err error) (bool, error) { if err == nil { return false, nil diff --git a/client/rpc_client.go b/client/rpc_client.go index e233ec1d68..6ce48727e0 100644 --- a/client/rpc_client.go +++ b/client/rpc_client.go @@ -320,7 +320,7 @@ func (r *rpcClient) Options() Options { return r.opts } -// next returns an iterator for the next nodes to call +// next returns an iterator for the next nodes to call. func (r *rpcClient) next(request Request, opts CallOptions) (selector.Next, error) { // try get the proxy service, address, _ := net.Proxy(request.Service(), opts.Address) diff --git a/client/rpc_client_test.go b/client/rpc_client_test.go index ac4bd1e02e..d276cfba6c 100644 --- a/client/rpc_client_test.go +++ b/client/rpc_client_test.go @@ -58,7 +58,6 @@ func TestCallAddress(t *testing.T) { if !called { t.Fatal("wrapper not called") } - } func TestCallRetry(t *testing.T) { diff --git a/client/rpc_codec.go b/client/rpc_codec.go index 6952471b93..7023873dab 100644 --- a/client/rpc_codec.go +++ b/client/rpc_codec.go @@ -28,7 +28,7 @@ func (e serverError) Error() string { return string(e) } -// errShutdown holds the specific error for closing/closed connections +// errShutdown holds the specific error for closing/closed connections. var ( errShutdown = errs.New("connection is shut down") ) @@ -63,7 +63,7 @@ var ( "application/octet-stream": raw.NewCodec, } - // TODO: remove legacy codec list + // TODO: remove legacy codec list. defaultCodecs = map[string]codec.NewCodec{ "application/json": jsonrpc.NewCodec, "application/json-rpc": jsonrpc.NewCodec, @@ -127,7 +127,7 @@ func setHeaders(m *codec.Message, stream string) { } } -// setupProtocol sets up the old protocol +// setupProtocol sets up the old protocol. func setupProtocol(msg *transport.Message, node *registry.Node) codec.NewCodec { protocol := node.Metadata["protocol"] diff --git a/client/rpc_stream.go b/client/rpc_stream.go index 515dc5b199..780658c3ac 100644 --- a/client/rpc_stream.go +++ b/client/rpc_stream.go @@ -9,7 +9,7 @@ import ( "go-micro.dev/v4/codec" ) -// Implements the streamer interface +// Implements the streamer interface. type rpcStream struct { sync.RWMutex id string diff --git a/client/wrapper.go b/client/wrapper.go index 4e7e3389c8..f332e8001a 100644 --- a/client/wrapper.go +++ b/client/wrapper.go @@ -6,14 +6,14 @@ import ( "go-micro.dev/v4/registry" ) -// CallFunc represents the individual call func +// CallFunc represents the individual call func. type CallFunc func(ctx context.Context, node *registry.Node, req Request, rsp interface{}, opts CallOptions) error -// CallWrapper is a low level wrapper for the CallFunc +// CallWrapper is a low level wrapper for the CallFunc. type CallWrapper func(CallFunc) CallFunc -// Wrapper wraps a client and returns a client +// Wrapper wraps a client and returns a client. type Wrapper func(Client) Client -// StreamWrapper wraps a Stream and returns the equivalent +// StreamWrapper wraps a Stream and returns the equivalent. type StreamWrapper func(Stream) Stream diff --git a/codec/bytes/bytes.go b/codec/bytes/bytes.go index 184d4446cd..580fb515c2 100644 --- a/codec/bytes/bytes.go +++ b/codec/bytes/bytes.go @@ -12,7 +12,7 @@ type Codec struct { Conn io.ReadWriteCloser } -// Frame gives us the ability to define raw data to send over the pipes +// Frame gives us the ability to define raw data to send over the pipes. type Frame struct { Data []byte } diff --git a/codec/codec.go b/codec/codec.go index 107bdb356f..8266f2f3a6 100644 --- a/codec/codec.go +++ b/codec/codec.go @@ -19,7 +19,7 @@ var ( type MessageType int -// Takes in a connection/buffer and returns a new Codec +// Takes in a connection/buffer and returns a new Codec. type NewCodec func(io.ReadWriteCloser) Codec // Codec encodes/decodes various types of messages used within go-micro. diff --git a/codec/grpc/grpc.go b/codec/grpc/grpc.go index 0e36425709..082aa9e129 100644 --- a/codec/grpc/grpc.go +++ b/codec/grpc/grpc.go @@ -89,7 +89,7 @@ func (c *Codec) Write(m *codec.Message, b interface{}) error { m.Header[":authority"] = m.Target m.Header["content-type"] = c.ContentType case codec.Response: - m.Header["Trailer"] = "grpc-status" //, grpc-message" + m.Header["Trailer"] = "grpc-status" // , grpc-message" m.Header["content-type"] = c.ContentType m.Header[":status"] = "200" m.Header["grpc-status"] = "0" diff --git a/codec/json/marshaler.go b/codec/json/marshaler.go index 2f6bcd54df..823409d2b2 100644 --- a/codec/json/marshaler.go +++ b/codec/json/marshaler.go @@ -11,7 +11,7 @@ import ( var jsonpbMarshaler = &jsonpb.Marshaler{} -// create buffer pool with 16 instances each preallocated with 256 bytes +// create buffer pool with 16 instances each preallocated with 256 bytes. var bufferPool = bpool.NewSizedBufferPool(16, 256) type Marshaler struct{} diff --git a/codec/jsonrpc/jsonrpc.go b/codec/jsonrpc/jsonrpc.go index 2ceffdb566..a4b2549713 100644 --- a/codec/jsonrpc/jsonrpc.go +++ b/codec/jsonrpc/jsonrpc.go @@ -41,7 +41,7 @@ func (j *jsonCodec) Write(m *codec.Message, b interface{}) error { _, err = j.rwc.Write(data) return err default: - return fmt.Errorf("Unrecognised message type: %v", m.Type) + return fmt.Errorf("Unrecognized message type: %v", m.Type) } } @@ -58,7 +58,7 @@ func (j *jsonCodec) ReadHeader(m *codec.Message, mt codec.MessageType) error { _, err := io.Copy(j.buf, j.rwc) return err default: - return fmt.Errorf("Unrecognised message type: %v", mt) + return fmt.Errorf("Unrecognized message type: %v", mt) } } @@ -73,7 +73,7 @@ func (j *jsonCodec) ReadBody(b interface{}) error { return json.Unmarshal(j.buf.Bytes(), b) } default: - return fmt.Errorf("Unrecognised message type: %v", j.mt) + return fmt.Errorf("Unrecognized message type: %v", j.mt) } return nil } diff --git a/codec/proto/marshaler.go b/codec/proto/marshaler.go index bb1eaea75c..889e6cbda4 100644 --- a/codec/proto/marshaler.go +++ b/codec/proto/marshaler.go @@ -8,7 +8,7 @@ import ( "go-micro.dev/v4/codec" ) -// create buffer pool with 16 instances each preallocated with 256 bytes +// create buffer pool with 16 instances each preallocated with 256 bytes. var bufferPool = bpool.NewSizedBufferPool(16, 256) type Marshaler struct{} diff --git a/codec/protorpc/protorpc.go b/codec/protorpc/protorpc.go index 165e085527..030093b42f 100644 --- a/codec/protorpc/protorpc.go +++ b/codec/protorpc/protorpc.go @@ -114,7 +114,7 @@ func (c *protoCodec) Write(m *codec.Message, b interface{}) error { } c.rwc.Write(data) default: - return fmt.Errorf("Unrecognised message type: %v", m.Type) + return fmt.Errorf("Unrecognized message type: %v", m.Type) } return nil } @@ -153,7 +153,7 @@ func (c *protoCodec) ReadHeader(m *codec.Message, mt codec.MessageType) error { _, err := io.Copy(c.buf, c.rwc) return err default: - return fmt.Errorf("Unrecognised message type: %v", mt) + return fmt.Errorf("Unrecognized message type: %v", mt) } return nil } @@ -170,7 +170,7 @@ func (c *protoCodec) ReadBody(b interface{}) error { case codec.Event: data = c.buf.Bytes() default: - return fmt.Errorf("Unrecognised message type: %v", c.mt) + return fmt.Errorf("Unrecognized message type: %v", c.mt) } if b != nil { return proto.Unmarshal(data, b.(proto.Message)) diff --git a/codec/text/text.go b/codec/text/text.go index 7de328a977..dda81dcb4b 100644 --- a/codec/text/text.go +++ b/codec/text/text.go @@ -12,7 +12,7 @@ type Codec struct { Conn io.ReadWriteCloser } -// Frame gives us the ability to define raw data to send over the pipes +// Frame gives us the ability to define raw data to send over the pipes. type Frame struct { Data []byte } diff --git a/config/config.go b/config/config.go index c6b1ed7976..ba4b6c4d9d 100644 --- a/config/config.go +++ b/config/config.go @@ -10,7 +10,7 @@ import ( "go-micro.dev/v4/config/source/file" ) -// Config is an interface abstraction for dynamic configuration +// Config is an interface abstraction for dynamic configuration. type Config interface { // provide the reader.Values interface reader.Values @@ -28,7 +28,7 @@ type Config interface { Watch(path ...string) (Watcher, error) } -// Watcher is the config watcher +// Watcher is the config watcher. type Watcher interface { Next() (reader.Value, error) Stop() error @@ -48,51 +48,51 @@ type Options struct { type Option func(o *Options) var ( - // Default Config Manager + // Default Config Manager. DefaultConfig, _ = NewConfig() ) -// NewConfig returns new config +// NewConfig returns new config. func NewConfig(opts ...Option) (Config, error) { return newConfig(opts...) } -// Return config as raw json +// Return config as raw json. func Bytes() []byte { return DefaultConfig.Bytes() } -// Return config as a map +// Return config as a map. func Map() map[string]interface{} { return DefaultConfig.Map() } -// Scan values to a go type +// Scan values to a go type. func Scan(v interface{}) error { return DefaultConfig.Scan(v) } -// Force a source changeset sync +// Force a source changeset sync. func Sync() error { return DefaultConfig.Sync() } -// Get a value from the config +// Get a value from the config. func Get(path ...string) reader.Value { return DefaultConfig.Get(path...) } -// Load config sources +// Load config sources. func Load(source ...source.Source) error { return DefaultConfig.Load(source...) } -// Watch a value for changes +// Watch a value for changes. func Watch(path ...string) (Watcher, error) { return DefaultConfig.Watch(path...) } -// LoadFile is short hand for creating a file source and loading it +// LoadFile is short hand for creating a file source and loading it. func LoadFile(path string) error { return Load(file.NewSource( file.WithPath(path), diff --git a/config/default.go b/config/default.go index a5863a4b79..4d813d694c 100644 --- a/config/default.go +++ b/config/default.go @@ -159,7 +159,7 @@ func (c *config) Scan(v interface{}) error { return c.vals.Scan(v) } -// sync loads all the sources, calls the parser and updates the config +// sync loads all the sources, calls the parser and updates the config. func (c *config) Sync() error { if err := c.opts.Loader.Sync(); err != nil { return err diff --git a/config/loader/loader.go b/config/loader/loader.go index 28d8e09374..7824320ff2 100644 --- a/config/loader/loader.go +++ b/config/loader/loader.go @@ -8,7 +8,7 @@ import ( "go-micro.dev/v4/config/source" ) -// Loader manages loading sources +// Loader manages loading sources. type Loader interface { // Stop the loader Close() error @@ -24,7 +24,7 @@ type Loader interface { String() string } -// Watcher lets you watch sources and returns a merged ChangeSet +// Watcher lets you watch sources and returns a merged ChangeSet. type Watcher interface { // First call to next may return the current Snapshot // If you are watching a path then only the data from @@ -34,7 +34,7 @@ type Watcher interface { Stop() error } -// Snapshot is a merged ChangeSet +// Snapshot is a merged ChangeSet. type Snapshot struct { // The merged ChangeSet ChangeSet *source.ChangeSet @@ -54,7 +54,7 @@ type Options struct { type Option func(o *Options) -// Copy snapshot +// Copy snapshot. func Copy(s *Snapshot) *Snapshot { cs := *(s.ChangeSet) diff --git a/config/loader/memory/memory.go b/config/loader/memory/memory.go index 8c1cb15353..f5a4002908 100644 --- a/config/loader/memory/memory.go +++ b/config/loader/memory/memory.go @@ -128,7 +128,7 @@ func (m *memory) loaded() bool { return loaded } -// reload reads the sets and creates new values +// reload reads the sets and creates new values. func (m *memory) reload() error { m.Lock() @@ -185,7 +185,7 @@ func (m *memory) update() { } } -// Snapshot returns a snapshot of the current loaded config +// Snapshot returns a snapshot of the current loaded config. func (m *memory) Snapshot() (*loader.Snapshot, error) { if m.loaded() { m.RLock() @@ -207,7 +207,7 @@ func (m *memory) Snapshot() (*loader.Snapshot, error) { return snap, nil } -// Sync loads all the sources, calls the parser and updates the config +// Sync loads all the sources, calls the parser and updates the config. func (m *memory) Sync() error { //nolint:prealloc var sets []*source.ChangeSet @@ -394,7 +394,6 @@ func (w *watcher) Next() (*loader.Snapshot, error) { ChangeSet: cs, Version: w.version, } - } for { diff --git a/config/loader/memory/options.go b/config/loader/memory/options.go index fe4add8dd9..65c3feb86a 100644 --- a/config/loader/memory/options.go +++ b/config/loader/memory/options.go @@ -6,14 +6,14 @@ import ( "go-micro.dev/v4/config/source" ) -// WithSource appends a source to list of sources +// WithSource appends a source to list of sources. func WithSource(s source.Source) loader.Option { return func(o *loader.Options) { o.Source = append(o.Source, s) } } -// WithReader sets the config reader +// WithReader sets the config reader. func WithReader(r reader.Reader) loader.Option { return func(o *loader.Options) { o.Reader = r diff --git a/config/options.go b/config/options.go index a231cdba32..d4994f5c05 100644 --- a/config/options.go +++ b/config/options.go @@ -6,21 +6,21 @@ import ( "go-micro.dev/v4/config/source" ) -// WithLoader sets the loader for manager config +// WithLoader sets the loader for manager config. func WithLoader(l loader.Loader) Option { return func(o *Options) { o.Loader = l } } -// WithSource appends a source to list of sources +// WithSource appends a source to list of sources. func WithSource(s source.Source) Option { return func(o *Options) { o.Source = append(o.Source, s) } } -// WithReader sets the config reader +// WithReader sets the config reader. func WithReader(r reader.Reader) Option { return func(o *Options) { o.Reader = r diff --git a/config/reader/json/json.go b/config/reader/json/json.go index aa891ff62b..259b14ac89 100644 --- a/config/reader/json/json.go +++ b/config/reader/json/json.go @@ -73,7 +73,7 @@ func (j *jsonReader) String() string { return "json" } -// NewReader creates a json reader +// NewReader creates a json reader. func NewReader(opts ...reader.Option) reader.Reader { options := reader.NewOptions(opts...) return &jsonReader{ diff --git a/config/reader/json/values.go b/config/reader/json/values.go index 8adb24a19d..a96194edf2 100644 --- a/config/reader/json/values.go +++ b/config/reader/json/values.go @@ -190,7 +190,7 @@ func (j *jsonValue) Scan(v interface{}) error { func (j *jsonValue) Bytes() []byte { b, err := j.Json.Bytes() if err != nil { - // try return marshalled + // try return marshaled b, err = j.Json.MarshalJSON() if err != nil { return []byte{} diff --git a/config/reader/reader.go b/config/reader/reader.go index d72c666cac..9a50462def 100644 --- a/config/reader/reader.go +++ b/config/reader/reader.go @@ -7,14 +7,14 @@ import ( "go-micro.dev/v4/config/source" ) -// Reader is an interface for merging changesets +// Reader is an interface for merging changesets. type Reader interface { Merge(...*source.ChangeSet) (*source.ChangeSet, error) Values(*source.ChangeSet) (Values, error) String() string } -// Values is returned by the reader +// Values is returned by the reader. type Values interface { Bytes() []byte Get(path ...string) Value @@ -24,7 +24,7 @@ type Values interface { Scan(v interface{}) error } -// Value represents a value of any type +// Value represents a value of any type. type Value interface { Bool(def bool) bool Int(def int) int diff --git a/config/secrets/box/box.go b/config/secrets/box/box.go index 97140f4be9..e5f32118ce 100644 --- a/config/secrets/box/box.go +++ b/config/secrets/box/box.go @@ -18,7 +18,7 @@ type box struct { privateKey [keyLength]byte } -// NewSecrets returns a nacl-box codec +// NewSecrets returns a nacl-box codec. func NewSecrets(opts ...secrets.Option) secrets.Secrets { b := &box{} for _, o := range opts { @@ -27,7 +27,6 @@ func NewSecrets(opts ...secrets.Option) secrets.Secrets { return b } -// Init initialises a box func (b *box) Init(opts ...secrets.Option) error { for _, o := range opts { o(&b.options) @@ -40,17 +39,17 @@ func (b *box) Init(opts ...secrets.Option) error { return nil } -// Options returns options +// Options returns options. func (b *box) Options() secrets.Options { return b.options } -// String returns nacl-box +// String returns nacl-box. func (*box) String() string { return "nacl-box" } -// Encrypt encrypts a message with the sender's private key and the receipient's public key +// Encrypt encrypts a message with the sender's private key and the receipient's public key. func (b *box) Encrypt(in []byte, opts ...secrets.EncryptOption) ([]byte, error) { var options secrets.EncryptOptions for _, o := range opts { @@ -68,7 +67,7 @@ func (b *box) Encrypt(in []byte, opts ...secrets.EncryptOption) ([]byte, error) return naclbox.Seal(nonce[:], in, &nonce, &recipientPublicKey, &b.privateKey), nil } -// Decrypt Decrypts a message with the receiver's private key and the sender's public key +// Decrypt Decrypts a message with the receiver's private key and the sender's public key. func (b *box) Decrypt(in []byte, opts ...secrets.DecryptOption) ([]byte, error) { var options secrets.DecryptOptions for _, o := range opts { diff --git a/config/secrets/box/box_test.go b/config/secrets/box/box_test.go index 89e2aab57a..0c15d4ec17 100644 --- a/config/secrets/box/box_test.go +++ b/config/secrets/box/box_test.go @@ -30,14 +30,14 @@ func TestBox(t *testing.T) { } aliceSecret := []byte("Why is a raven like a writing-desk?") if _, err := alice.Encrypt(aliceSecret); err == nil { - t.Error("alice.Encrypt succeded without a public key") + t.Error("alice.Encrypt succeeded without a public key") } enc, err := alice.Encrypt(aliceSecret, secrets.RecipientPublicKey(bob.Options().PublicKey)) if err != nil { t.Error("alice.Encrypt failed") } if _, err := bob.Decrypt(enc); err == nil { - t.Error("bob.Decrypt succeded without a public key") + t.Error("bob.Decrypt succeeded without a public key") } if dec, err := bob.Decrypt(enc, secrets.SenderPublicKey(alice.Options().PublicKey)); err == nil { if !reflect.DeepEqual(dec, aliceSecret) { diff --git a/config/secrets/secretbox/secretbox.go b/config/secrets/secretbox/secretbox.go index 9e49a028c8..3443f598f6 100644 --- a/config/secrets/secretbox/secretbox.go +++ b/config/secrets/secretbox/secretbox.go @@ -18,7 +18,7 @@ type secretBox struct { secretKey [keyLength]byte } -// NewSecrets returns a secretbox codec +// NewSecrets returns a secretbox codec. func NewSecrets(opts ...secrets.Option) secrets.Secrets { sb := &secretBox{} for _, o := range opts { diff --git a/config/secrets/secrets.go b/config/secrets/secrets.go index c85513555a..56c3ec9384 100644 --- a/config/secrets/secrets.go +++ b/config/secrets/secrets.go @@ -3,9 +3,9 @@ package secrets import "context" -// Secrets encrypts or decrypts arbitrary data. The data should be as small as possible +// Secrets encrypts or decrypts arbitrary data. The data should be as small as possible. type Secrets interface { - // Initialise options + // Initialize options Init(...Option) error // Return the options Options() Options @@ -28,10 +28,10 @@ type Options struct { Context context.Context } -// Option sets options +// Option sets options. type Option func(*Options) -// Key sets the symmetric secret key +// Key sets the symmetric secret key. func Key(k []byte) Option { return func(o *Options) { o.Key = make([]byte, len(k)) @@ -39,7 +39,7 @@ func Key(k []byte) Option { } } -// PublicKey sets the asymmetric Public Key of this codec +// PublicKey sets the asymmetric Public Key of this codec. func PublicKey(key []byte) Option { return func(o *Options) { o.PublicKey = make([]byte, len(key)) @@ -47,7 +47,7 @@ func PublicKey(key []byte) Option { } } -// PrivateKey sets the asymmetric Private Key of this codec +// PrivateKey sets the asymmetric Private Key of this codec. func PrivateKey(key []byte) Option { return func(o *Options) { o.PrivateKey = make([]byte, len(key)) @@ -55,15 +55,15 @@ func PrivateKey(key []byte) Option { } } -// DecryptOptions can be passed to Secrets.Decrypt +// DecryptOptions can be passed to Secrets.Decrypt. type DecryptOptions struct { SenderPublicKey []byte } -// DecryptOption sets DecryptOptions +// DecryptOption sets DecryptOptions. type DecryptOption func(*DecryptOptions) -// SenderPublicKey is the Public Key of the Secrets that encrypted this message +// SenderPublicKey is the Public Key of the Secrets that encrypted this message. func SenderPublicKey(key []byte) DecryptOption { return func(d *DecryptOptions) { d.SenderPublicKey = make([]byte, len(key)) @@ -71,15 +71,15 @@ func SenderPublicKey(key []byte) DecryptOption { } } -// EncryptOptions can be passed to Secrets.Encrypt +// EncryptOptions can be passed to Secrets.Encrypt. type EncryptOptions struct { RecipientPublicKey []byte } -// EncryptOption Sets EncryptOptions +// EncryptOption Sets EncryptOptions. type EncryptOption func(*EncryptOptions) -// RecipientPublicKey is the Public Key of the Secrets that will decrypt this message +// RecipientPublicKey is the Public Key of the Secrets that will decrypt this message. func RecipientPublicKey(key []byte) EncryptOption { return func(e *EncryptOptions) { e.RecipientPublicKey = make([]byte, len(key)) diff --git a/config/source/changeset.go b/config/source/changeset.go index 9958f61d8a..44ef64a94d 100644 --- a/config/source/changeset.go +++ b/config/source/changeset.go @@ -5,7 +5,7 @@ import ( "fmt" ) -// Sum returns the md5 checksum of the ChangeSet data +// Sum returns the md5 checksum of the ChangeSet data. func (c *ChangeSet) Sum() string { h := md5.New() h.Write(c.Data) diff --git a/config/source/cli/cli.go b/config/source/cli/cli.go index ad94fda394..b12d2d9ff1 100644 --- a/config/source/cli/cli.go +++ b/config/source/cli/cli.go @@ -75,7 +75,7 @@ func (c *cliSource) Watch() (source.Watcher, error) { return source.NewNoopWatcher() } -// Write is unsupported +// Write is unsupported. func (c *cliSource) Write(cs *source.ChangeSet) error { return nil } diff --git a/config/source/cli/cli_test.go b/config/source/cli/cli_test.go index 871960d189..26392e5989 100644 --- a/config/source/cli/cli_test.go +++ b/config/source/cli/cli_test.go @@ -104,7 +104,6 @@ func test(t *testing.T, withContext bool) { if actualDB["host"] != "localhost" { t.Errorf("expected localhost, got %v", actualDB["name"]) } - } func TestCliSource(t *testing.T) { diff --git a/config/source/cli/options.go b/config/source/cli/options.go index 9f75b0a2fa..8ceaa90bef 100644 --- a/config/source/cli/options.go +++ b/config/source/cli/options.go @@ -9,7 +9,7 @@ import ( type contextKey struct{} -// Context sets the cli context +// Context sets the cli context. func Context(c *cli.Context) source.Option { return func(o *source.Options) { if o.Context == nil { diff --git a/config/source/env/env.go b/config/source/env/env.go index 24976192b7..b7b0ff516f 100644 --- a/config/source/env/env.go +++ b/config/source/env/env.go @@ -24,7 +24,6 @@ func (e *env) Read() (*source.ChangeSet, error) { var changes map[string]interface{} for _, env := range os.Environ() { - if len(e.prefixes) > 0 || len(e.strippedPrefixes) > 0 { notFound := true diff --git a/config/source/file/format_test.go b/config/source/file/format_test.go index 24441df5ec..2f4177d622 100644 --- a/config/source/file/format_test.go +++ b/config/source/file/format_test.go @@ -27,5 +27,4 @@ func TestFormat(t *testing.T) { t.Fatalf("%s: expected %s got %s", d.p, d.f, f) } } - } diff --git a/config/source/file/options.go b/config/source/file/options.go index be55ed99cd..b28bde3327 100644 --- a/config/source/file/options.go +++ b/config/source/file/options.go @@ -10,7 +10,7 @@ import ( type filePathKey struct{} type fsKey struct{} -// WithPath sets the path to file +// WithPath sets the path to file. func WithPath(p string) source.Option { return func(o *source.Options) { if o.Context == nil { @@ -20,7 +20,7 @@ func WithPath(p string) source.Option { } } -// WithFS sets the underlying filesystem to lookup file from (default os.FS) +// WithFS sets the underlying filesystem to lookup file from (default os.FS). func WithFS(fs fs.FS) source.Option { return func(o *source.Options) { if o.Context == nil { diff --git a/config/source/flag/flag.go b/config/source/flag/flag.go index b299657672..eda7a6eb45 100644 --- a/config/source/flag/flag.go +++ b/config/source/flag/flag.go @@ -3,10 +3,11 @@ package flag import ( "errors" "flag" - "github.com/imdario/mergo" - "go-micro.dev/v4/config/source" "strings" "time" + + "github.com/imdario/mergo" + "go-micro.dev/v4/config/source" ) type flagsrc struct { diff --git a/config/source/memory/options.go b/config/source/memory/options.go index 02d1994821..988dde26d0 100644 --- a/config/source/memory/options.go +++ b/config/source/memory/options.go @@ -20,7 +20,7 @@ func withData(d []byte, f string) source.Option { } } -// WithChangeSet allows a changeset to be set +// WithChangeSet allows a changeset to be set. func WithChangeSet(cs *source.ChangeSet) source.Option { return func(o *source.Options) { if o.Context == nil { @@ -30,12 +30,12 @@ func WithChangeSet(cs *source.ChangeSet) source.Option { } } -// WithJSON allows the source data to be set to json +// WithJSON allows the source data to be set to json. func WithJSON(d []byte) source.Option { return withData(d, "json") } -// WithYAML allows the source data to be set to yaml +// WithYAML allows the source data to be set to yaml. func WithYAML(d []byte) source.Option { return withData(d, "yaml") } diff --git a/config/source/options.go b/config/source/options.go index 742edf4524..996e6c301e 100644 --- a/config/source/options.go +++ b/config/source/options.go @@ -35,14 +35,14 @@ func NewOptions(opts ...Option) Options { return options } -// WithEncoder sets the source encoder +// WithEncoder sets the source encoder. func WithEncoder(e encoder.Encoder) Option { return func(o *Options) { o.Encoder = e } } -// WithClient sets the source client +// WithClient sets the source client. func WithClient(c client.Client) Option { return func(o *Options) { o.Client = c diff --git a/config/source/source.go b/config/source/source.go index 0cf8b9fb47..398a4bae14 100644 --- a/config/source/source.go +++ b/config/source/source.go @@ -7,11 +7,11 @@ import ( ) var ( - // ErrWatcherStopped is returned when source watcher has been stopped + // ErrWatcherStopped is returned when source watcher has been stopped. ErrWatcherStopped = errors.New("watcher stopped") ) -// Source is the source from which config is loaded +// Source is the source from which config is loaded. type Source interface { Read() (*ChangeSet, error) Write(*ChangeSet) error @@ -19,7 +19,7 @@ type Source interface { String() string } -// ChangeSet represents a set of changes from a source +// ChangeSet represents a set of changes from a source. type ChangeSet struct { Data []byte Checksum string @@ -28,7 +28,7 @@ type ChangeSet struct { Timestamp time.Time } -// Watcher watches a source for changes +// Watcher watches a source for changes. type Watcher interface { Next() (*ChangeSet, error) Stop() error diff --git a/debug/handler/debug.go b/debug/handler/debug.go index dce67c8f68..cb470a0937 100644 --- a/debug/handler/debug.go +++ b/debug/handler/debug.go @@ -13,7 +13,7 @@ import ( "go-micro.dev/v4/server" ) -// NewHandler returns an instance of the Debug Handler +// NewHandler returns an instance of the Debug Handler. func NewHandler(c client.Client) *Debug { return &Debug{ log: log.DefaultLog, @@ -23,7 +23,7 @@ func NewHandler(c client.Client) *Debug { } type Debug struct { - // must honour the debug handler + // must honor the debug handler proto.DebugHandler // the logger for retrieving logs log log.Log diff --git a/debug/log/log.go b/debug/log/log.go index bf90a9994c..29681eec67 100644 --- a/debug/log/log.go +++ b/debug/log/log.go @@ -8,15 +8,15 @@ import ( ) var ( - // Default buffer size if any + // Default buffer size if any. DefaultSize = 1024 - // DefaultLog logger + // DefaultLog logger. DefaultLog = NewLog() - // Default formatter + // Default formatter. DefaultFormat = TextFormat ) -// Log is debug log interface for reading and writing logs +// Log is debug log interface for reading and writing logs. type Log interface { // Read reads log entries from the logger Read(...ReadOption) ([]Record, error) @@ -26,7 +26,7 @@ type Log interface { Stream() (Stream, error) } -// Record is log record entry +// Record is log record entry. type Record struct { // Timestamp of logged event Timestamp time.Time `json:"timestamp"` @@ -36,22 +36,22 @@ type Record struct { Message interface{} `json:"message"` } -// Stream returns a log stream +// Stream returns a log stream. type Stream interface { Chan() <-chan Record Stop() error } -// Format is a function which formats the output +// Format is a function which formats the output. type FormatFunc func(Record) string -// TextFormat returns text format +// TextFormat returns text format. func TextFormat(r Record) string { t := r.Timestamp.Format("2006-01-02 15:04:05") return fmt.Sprintf("%s %v", t, r.Message) } -// JSONFormat is a json Format func +// JSONFormat is a json Format func. func JSONFormat(r Record) string { b, _ := json.Marshal(r) return string(b) diff --git a/debug/log/memory/memory.go b/debug/log/memory/memory.go index 326fd4b111..8f9c7a85ac 100644 --- a/debug/log/memory/memory.go +++ b/debug/log/memory/memory.go @@ -9,16 +9,16 @@ import ( ) var ( - // DefaultSize of the logger buffer + // DefaultSize of the logger buffer. DefaultSize = 1024 ) -// memoryLog is default micro log +// memoryLog is default micro log. type memoryLog struct { *ring.Buffer } -// NewLog returns default Logger with +// NewLog returns default Logger with. func NewLog(opts ...log.Option) log.Log { // get default options options := log.DefaultOptions() @@ -33,13 +33,13 @@ func NewLog(opts ...log.Option) log.Log { } } -// Write writes logs into logger +// Write writes logs into logger. func (l *memoryLog) Write(r log.Record) error { l.Buffer.Put(fmt.Sprint(r.Message)) return nil } -// Read reads logs and returns them +// Read reads logs and returns them. func (l *memoryLog) Read(opts ...log.ReadOption) ([]log.Record, error) { options := log.ReadOptions{} // initialize the read options @@ -83,7 +83,7 @@ func (l *memoryLog) Read(opts ...log.ReadOption) ([]log.Record, error) { } // Stream returns channel for reading log records -// along with a stop channel, close it when done +// along with a stop channel, close it when done. func (l *memoryLog) Stream() (log.Stream, error) { // get stream channel from ring buffer stream, stop := l.Buffer.Stream() diff --git a/debug/log/options.go b/debug/log/options.go index 632818578e..e03a70b088 100644 --- a/debug/log/options.go +++ b/debug/log/options.go @@ -2,10 +2,10 @@ package log import "time" -// Option used by the logger +// Option used by the logger. type Option func(*Options) -// Options are logger options +// Options are logger options. type Options struct { // Name of the log Name string @@ -15,14 +15,14 @@ type Options struct { Format FormatFunc } -// Name of the log +// Name of the log. func Name(n string) Option { return func(o *Options) { o.Name = n } } -// Size sets the size of the ring buffer +// Size sets the size of the ring buffer. func Size(s int) Option { return func(o *Options) { o.Size = s @@ -35,14 +35,14 @@ func Format(f FormatFunc) Option { } } -// DefaultOptions returns default options +// DefaultOptions returns default options. func DefaultOptions() Options { return Options{ Size: DefaultSize, } } -// ReadOptions for querying the logs +// ReadOptions for querying the logs. type ReadOptions struct { // Since what time in past to return the logs Since time.Time @@ -52,17 +52,17 @@ type ReadOptions struct { Stream bool } -// ReadOption used for reading the logs +// ReadOption used for reading the logs. type ReadOption func(*ReadOptions) -// Since sets the time since which to return the log records +// Since sets the time since which to return the log records. func Since(s time.Time) ReadOption { return func(o *ReadOptions) { o.Since = s } } -// Count sets the number of log records to return +// Count sets the number of log records to return. func Count(c int) ReadOption { return func(o *ReadOptions) { o.Count = c diff --git a/debug/log/os.go b/debug/log/os.go index 3a6d325284..55cc4bdfca 100644 --- a/debug/log/os.go +++ b/debug/log/os.go @@ -7,7 +7,7 @@ import ( "go-micro.dev/v4/util/ring" ) -// Should stream from OS +// Should stream from OS. type osLog struct { format FormatFunc once sync.Once @@ -21,7 +21,7 @@ type osStream struct { stream chan Record } -// Read reads log entries from the logger +// Read reads log entries from the logger. func (o *osLog) Read(...ReadOption) ([]Record, error) { var records []Record @@ -33,13 +33,13 @@ func (o *osLog) Read(...ReadOption) ([]Record, error) { return records, nil } -// Write writes records to log +// Write writes records to log. func (o *osLog) Write(r Record) error { o.buffer.Put(r) return nil } -// Stream log records +// Stream log records. func (o *osLog) Stream() (Stream, error) { o.Lock() defer o.Unlock() diff --git a/debug/profile/http/http.go b/debug/profile/http/http.go index fa2da3ceb2..8931487e18 100644 --- a/debug/profile/http/http.go +++ b/debug/profile/http/http.go @@ -20,7 +20,7 @@ var ( DefaultAddress = ":6060" ) -// Start the profiler +// Start the profiler. func (h *httpProfile) Start() error { h.Lock() defer h.Unlock() @@ -42,7 +42,7 @@ func (h *httpProfile) Start() error { return nil } -// Stop the profiler +// Stop the profiler. func (h *httpProfile) Stop() error { h.Lock() defer h.Unlock() diff --git a/debug/profile/profile.go b/debug/profile/profile.go index d043e52424..df10af943e 100644 --- a/debug/profile/profile.go +++ b/debug/profile/profile.go @@ -35,7 +35,7 @@ type Options struct { type Option func(o *Options) -// Name of the profile +// Name of the profile. func Name(n string) Option { return func(o *Options) { o.Name = n diff --git a/debug/stats/default.go b/debug/stats/default.go index 7bf91aec82..6e547c9138 100644 --- a/debug/stats/default.go +++ b/debug/stats/default.go @@ -80,7 +80,7 @@ func (s *stats) Record(err error) error { } // NewStats returns a new in memory stats buffer -// TODO add options +// TODO add options. func NewStats() Stats { return &stats{ started: time.Now().Unix(), diff --git a/debug/stats/stats.go b/debug/stats/stats.go index 6cbf4b16fe..29df3e266d 100644 --- a/debug/stats/stats.go +++ b/debug/stats/stats.go @@ -1,7 +1,7 @@ // Package stats provides runtime stats package stats -// Stats provides stats interface +// Stats provides stats interface. type Stats interface { // Read stat snapshot Read() ([]*Stat, error) @@ -11,7 +11,7 @@ type Stats interface { Record(error) error } -// A runtime stat +// A runtime stat. type Stat struct { // Timestamp of recording Timestamp int64 diff --git a/debug/trace/options.go b/debug/trace/options.go index c7a6285fb2..bc9b14be26 100644 --- a/debug/trace/options.go +++ b/debug/trace/options.go @@ -14,7 +14,7 @@ type ReadOptions struct { type ReadOption func(o *ReadOptions) -// Read the given trace +// Read the given trace. func ReadTrace(t string) ReadOption { return func(o *ReadOptions) { o.Trace = t @@ -22,11 +22,11 @@ func ReadTrace(t string) ReadOption { } const ( - // DefaultSize of the buffer + // DefaultSize of the buffer. DefaultSize = 64 ) -// DefaultOptions returns default options +// DefaultOptions returns default options. func DefaultOptions() Options { return Options{ Size: DefaultSize, diff --git a/debug/trace/trace.go b/debug/trace/trace.go index 1275bb678e..26c187d37c 100644 --- a/debug/trace/trace.go +++ b/debug/trace/trace.go @@ -8,7 +8,7 @@ import ( "go-micro.dev/v4/metadata" ) -// Tracer is an interface for distributed tracing +// Tracer is an interface for distributed tracing. type Tracer interface { // Start a trace Start(ctx context.Context, name string) (context.Context, *Span) @@ -18,17 +18,17 @@ type Tracer interface { Read(...ReadOption) ([]*Span, error) } -// SpanType describe the nature of the trace span +// SpanType describe the nature of the trace span. type SpanType int const ( - // SpanTypeRequestInbound is a span created when serving a request + // SpanTypeRequestInbound is a span created when serving a request. SpanTypeRequestInbound SpanType = iota - // SpanTypeRequestOutbound is a span created when making a service call + // SpanTypeRequestOutbound is a span created when making a service call. SpanTypeRequestOutbound ) -// Span is used to record an entry +// Span is used to record an entry. type Span struct { // Id of the trace Trace string @@ -53,7 +53,7 @@ const ( spanIDKey = "Micro-Span-Id" ) -// FromContext returns a span from context +// FromContext returns a span from context. func FromContext(ctx context.Context) (traceID string, parentSpanID string, isFound bool) { traceID, traceOk := metadata.Get(ctx, traceIDKey) microID, microOk := metadata.Get(ctx, "Micro-Id") @@ -68,7 +68,7 @@ func FromContext(ctx context.Context) (traceID string, parentSpanID string, isFo return traceID, parentSpanID, ok } -// ToContext saves the trace and span ids in the context +// ToContext saves the trace and span ids in the context. func ToContext(ctx context.Context, traceID, parentSpanID string) context.Context { return metadata.MergeContext(ctx, map[string]string{ traceIDKey: traceID, diff --git a/errors/errors.go b/errors/errors.go index 01563208ae..f48fbe9510 100644 --- a/errors/errors.go +++ b/errors/errors.go @@ -117,7 +117,7 @@ func InternalServerError(id, format string, a ...interface{}) error { } } -// Equal tries to compare errors +// Equal tries to compare errors. func Equal(err1 error, err2 error) bool { verr1, ok1 := err1.(*Error) verr2, ok2 := err2.(*Error) @@ -137,7 +137,7 @@ func Equal(err1 error, err2 error) bool { return true } -// FromError try to convert go error to *Error +// FromError try to convert go error to *Error. func FromError(err error) *Error { if err == nil { return nil @@ -149,7 +149,7 @@ func FromError(err error) *Error { return Parse(err.Error()) } -// As finds the first error in err's chain that matches *Error +// As finds the first error in err's chain that matches *Error. func As(err error) (*Error, bool) { if err == nil { return nil, false diff --git a/errors/errors_test.go b/errors/errors_test.go index d6122c3161..f50ec7a446 100644 --- a/errors/errors_test.go +++ b/errors/errors_test.go @@ -35,7 +35,6 @@ func TestEqual(t *testing.T) { if Equal(err1, err3) { t.Fatal("errors must be not equal") } - } func TestErrors(t *testing.T) { diff --git a/events/events.go b/events/events.go index 77bb3df7fd..8c2dbf884d 100644 --- a/events/events.go +++ b/events/events.go @@ -8,26 +8,26 @@ import ( ) var ( - // DefaultStream is the default events stream implementation + // DefaultStream is the default events stream implementation. DefaultStream Stream - // DefaultStore is the default events store implementation + // DefaultStore is the default events store implementation. DefaultStore Store ) var ( - // ErrMissingTopic is returned if a blank topic was provided to publish + // ErrMissingTopic is returned if a blank topic was provided to publish. ErrMissingTopic = errors.New("Missing topic") - // ErrEncodingMessage is returned from publish if there was an error encoding the message option + // ErrEncodingMessage is returned from publish if there was an error encoding the message option. ErrEncodingMessage = errors.New("Error encoding message") ) -// Stream is an event streaming interface +// Stream is an event streaming interface. type Stream interface { Publish(topic string, msg interface{}, opts ...PublishOption) error Consume(topic string, opts ...ConsumeOption) (<-chan Event, error) } -// Store is an event store interface +// Store is an event store interface. type Store interface { Read(topic string, opts ...ReadOption) ([]*Event, error) Write(event *Event, opts ...WriteOption) error @@ -36,7 +36,7 @@ type Store interface { type AckFunc func() error type NackFunc func() error -// Event is the object returned by the broker when you subscribe to a topic +// Event is the object returned by the broker when you subscribe to a topic. type Event struct { // ID to uniquely identify the event ID string @@ -53,12 +53,12 @@ type Event struct { nackFunc NackFunc } -// Unmarshal the events message into an object +// Unmarshal the events message into an object. func (e *Event) Unmarshal(v interface{}) error { return json.Unmarshal(e.Payload, v) } -// Ack acknowledges successful processing of the event in ManualAck mode +// Ack acknowledges successful processing of the event in ManualAck mode. func (e *Event) Ack() error { return e.ackFunc() } @@ -67,7 +67,7 @@ func (e *Event) SetAckFunc(f AckFunc) { e.ackFunc = f } -// Nack negatively acknowledges processing of the event (i.e. failure) in ManualAck mode +// Nack negatively acknowledges processing of the event (i.e. failure) in ManualAck mode. func (e *Event) Nack() error { return e.nackFunc() } @@ -76,17 +76,17 @@ func (e *Event) SetNackFunc(f NackFunc) { e.nackFunc = f } -// Publish an event to a topic +// Publish an event to a topic. func Publish(topic string, msg interface{}, opts ...PublishOption) error { return DefaultStream.Publish(topic, msg, opts...) } -// Consume to events +// Consume to events. func Consume(topic string, opts ...ConsumeOption) (<-chan Event, error) { return DefaultStream.Consume(topic, opts...) } -// Read events for a topic +// Read events for a topic. func Read(topic string, opts ...ReadOption) ([]*Event, error) { return DefaultStore.Read(topic, opts...) } diff --git a/events/memory.go b/events/memory.go index 0a6b744342..113f2eef23 100644 --- a/events/memory.go +++ b/events/memory.go @@ -13,7 +13,7 @@ import ( "go-micro.dev/v4/store" ) -// NewStream returns an initialized memory stream +// NewStream returns an initialized memory stream. func NewStream(opts ...Option) (Stream, error) { // parse the options options := NewOptions(opts...) @@ -143,7 +143,7 @@ func (m *mem) Consume(topic string, opts ...ConsumeOption) (<-chan Event, error) } // lookupPreviousEvents finds events for a subscriber which occurred before a given time and sends -// them into the subscribers channel +// them into the subscribers channel. func (m *mem) lookupPreviousEvents(sub *subscriber, startTime time.Time) { // lookup all events which match the topic (a blank topic will return all results) recs, err := m.store.Read(sub.Topic+"/", store.ReadPrefix()) diff --git a/events/options.go b/events/options.go index 7b225a5132..d0ff17eb43 100644 --- a/events/options.go +++ b/events/options.go @@ -32,14 +32,14 @@ type StoreOptions struct { type StoreOption func(o *StoreOptions) -// WithLogger sets the underline logger +// WithLogger sets the underline logger. func WithLogger(l logger.Logger) StoreOption { return func(o *StoreOptions) { o.Logger = l } } -// PublishOptions contains all the options which can be provided when publishing an event +// PublishOptions contains all the options which can be provided when publishing an event. type PublishOptions struct { // Metadata contains any keys which can be used to query the data, for example a customer id Metadata map[string]string @@ -47,24 +47,24 @@ type PublishOptions struct { Timestamp time.Time } -// PublishOption sets attributes on PublishOptions +// PublishOption sets attributes on PublishOptions. type PublishOption func(o *PublishOptions) -// WithMetadata sets the Metadata field on PublishOptions +// WithMetadata sets the Metadata field on PublishOptions. func WithMetadata(md map[string]string) PublishOption { return func(o *PublishOptions) { o.Metadata = md } } -// WithTimestamp sets the timestamp field on PublishOptions +// WithTimestamp sets the timestamp field on PublishOptions. func WithTimestamp(t time.Time) PublishOption { return func(o *PublishOptions) { o.Timestamp = t } } -// ConsumeOptions contains all the options which can be provided when subscribing to a topic +// ConsumeOptions contains all the options which can be provided when subscribing to a topic. type ConsumeOptions struct { // Group is the name of the consumer group, if two consumers have the same group the events // are distributed between them @@ -85,17 +85,17 @@ type ConsumeOptions struct { CustomRetries bool } -// ConsumeOption sets attributes on ConsumeOptions +// ConsumeOption sets attributes on ConsumeOptions. type ConsumeOption func(o *ConsumeOptions) -// WithGroup sets the consumer group to be part of when consuming events +// WithGroup sets the consumer group to be part of when consuming events. func WithGroup(q string) ConsumeOption { return func(o *ConsumeOptions) { o.Group = q } } -// WithOffset sets the offset time at which to start consuming events +// WithOffset sets the offset time at which to start consuming events. func WithOffset(t time.Time) ConsumeOption { return func(o *ConsumeOptions) { o.Offset = t @@ -103,7 +103,7 @@ func WithOffset(t time.Time) ConsumeOption { } // WithAutoAck sets the AutoAck field on ConsumeOptions and an ackWait duration after which if no ack is received -// the message is requeued in case auto ack is turned off +// the message is requeued in case auto ack is turned off. func WithAutoAck(ack bool, ackWait time.Duration) ConsumeOption { return func(o *ConsumeOptions) { o.AutoAck = ack @@ -112,7 +112,7 @@ func WithAutoAck(ack bool, ackWait time.Duration) ConsumeOption { } // WithRetryLimit sets the RetryLimit field on ConsumeOptions. -// Set to -1 for infinite retries (default) +// Set to -1 for infinite retries (default). func WithRetryLimit(retries int) ConsumeOption { return func(o *ConsumeOptions) { o.RetryLimit = retries @@ -127,24 +127,24 @@ func (s ConsumeOptions) GetRetryLimit() int { return s.RetryLimit } -// WriteOptions contains all the options which can be provided when writing an event to a store +// WriteOptions contains all the options which can be provided when writing an event to a store. type WriteOptions struct { // TTL is the duration the event should be recorded for, a zero value TTL indicates the event should - // be stored indefinately + // be stored indefinitely TTL time.Duration } -// WriteOption sets attributes on WriteOptions +// WriteOption sets attributes on WriteOptions. type WriteOption func(o *WriteOptions) -// WithTTL sets the TTL attribute on WriteOptions +// WithTTL sets the TTL attribute on WriteOptions. func WithTTL(d time.Duration) WriteOption { return func(o *WriteOptions) { o.TTL = d } } -// ReadOptions contains all the options which can be provided when reading events from a store +// ReadOptions contains all the options which can be provided when reading events from a store. type ReadOptions struct { // Limit the number of results to return Limit uint @@ -152,17 +152,17 @@ type ReadOptions struct { Offset uint } -// ReadOption sets attributes on ReadOptions +// ReadOption sets attributes on ReadOptions. type ReadOption func(o *ReadOptions) -// ReadLimit sets the limit attribute on ReadOptions +// ReadLimit sets the limit attribute on ReadOptions. func ReadLimit(l uint) ReadOption { return func(o *ReadOptions) { o.Limit = 1 } } -// ReadOffset sets the offset attribute on ReadOptions +// ReadOffset sets the offset attribute on ReadOptions. func ReadOffset(l uint) ReadOption { return func(o *ReadOptions) { o.Offset = 1 diff --git a/events/store.go b/events/store.go index 58ab326799..2500522828 100644 --- a/events/store.go +++ b/events/store.go @@ -12,7 +12,7 @@ import ( const joinKey = "/" -// NewStore returns an initialized events store +// NewStore returns an initialized events store. func NewStore(opts ...StoreOption) Store { // parse the options var options StoreOptions @@ -41,7 +41,7 @@ type evStore struct { store store.Store } -// Read events for a topic +// Read events for a topic. func (s *evStore) Read(topic string, opts ...ReadOption) ([]*Event, error) { // validate the topic if len(topic) == 0 { @@ -80,7 +80,7 @@ func (s *evStore) Read(topic string, opts ...ReadOption) ([]*Event, error) { return result, nil } -// Write an event to the store +// Write an event to the store. func (s *evStore) Write(event *Event, opts ...WriteOption) error { // parse the options options := WriteOptions{ @@ -124,7 +124,7 @@ func (s *evStore) backupLoop() { } } -// Backup is an interface for snapshotting the events store to long term storage +// Backup is an interface for snapshotting the events store to long term storage. type Backup interface { Snapshot(st store.Store) error } diff --git a/events/store_test.go b/events/store_test.go index 9857ded64a..817c1f83af 100644 --- a/events/store_test.go +++ b/events/store_test.go @@ -43,7 +43,7 @@ func TestStore(t *testing.T) { assert.Len(t, evs, 2, "Only the events for this topic should be returned") }) - // limits should be honoured + // limits should be honored t.Run("ReadTopicLimit", func(t *testing.T) { t.Parallel() evs, err := store.Read("foo", ReadLimit(1)) diff --git a/events/stream_test.go b/events/stream_test.go index e3ee446d79..6d58f25441 100644 --- a/events/stream_test.go +++ b/events/stream_test.go @@ -34,7 +34,6 @@ func TestStream(t *testing.T) { runTestStream(t, tc.str) }) } - } func runTestStream(t *testing.T, stream Stream) { @@ -76,7 +75,7 @@ func runTestStream(t *testing.T, stream Stream) { wg.Done() case <-timeout.C: - t.Fatalf("Event was not recieved") + t.Fatalf("Event was not received") } }() @@ -84,7 +83,7 @@ func runTestStream(t *testing.T, stream Stream) { assert.Nil(t, err, "Publishing a valid message should not return an error") wg.Add(1) - // wait for the subscriber to recieve the message or timeout + // wait for the subscriber to receive the message or timeout wg.Wait() }) @@ -120,7 +119,7 @@ func runTestStream(t *testing.T, stream Stream) { wg.Done() case <-timeout.C: - t.Fatalf("Event was not recieved") + t.Fatalf("Event was not received") } }() @@ -150,11 +149,11 @@ func runTestStream(t *testing.T, stream Stream) { wg.Done() case <-timeout.C: - t.Fatalf("Event was not recieved") + t.Fatalf("Event was not received") } }() - // wait for the subscriber to recieve the message or timeout + // wait for the subscriber to receive the message or timeout wg.Wait() }) @@ -178,7 +177,6 @@ func runTestStream(t *testing.T, stream Stream) { case <-time.After(7 * time.Second): t.Fatalf("Timed out waiting for message to be put back on queue") } - }) t.Run("Retries", func(t *testing.T) { diff --git a/logger/default.go b/logger/default.go index a4f19f720d..d517e9ea62 100644 --- a/logger/default.go +++ b/logger/default.go @@ -27,7 +27,7 @@ type defaultLogger struct { opts Options } -// Init (opts...) should only overwrite provided options +// Init (opts...) should only overwrite provided options. func (l *defaultLogger) Init(opts ...Option) error { for _, o := range opts { o(&l.opts) @@ -183,7 +183,7 @@ func (l *defaultLogger) Options() Options { return opts } -// NewLogger builds a new logger based on options +// NewLogger builds a new logger based on options. func NewLogger(opts ...Option) Logger { // Default options options := Options{ diff --git a/logger/level.go b/logger/level.go index 915f0d47e5..328eb7bde4 100644 --- a/logger/level.go +++ b/logger/level.go @@ -116,7 +116,7 @@ func Fatalf(template string, args ...interface{}) { os.Exit(1) } -// Returns true if the given level is at or lower the current logger level +// Returns true if the given level is at or lower the current logger level. func V(lvl Level, log Logger) bool { l := DefaultLogger if log != nil { diff --git a/logger/logger.go b/logger/logger.go index e10d167bcf..059a4d7ae8 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -2,16 +2,16 @@ package logger var ( - // Default logger + // Default logger. DefaultLogger Logger = NewLogger() - // Default logger helper + // Default logger helper. DefaultHelper *Helper = NewHelper(DefaultLogger) ) -// Logger is a generic logging interface +// Logger is a generic logging interface. type Logger interface { - // Init initialises options + // Init initializes options Init(options ...Option) error // The Logger options Options() Options diff --git a/logger/options.go b/logger/options.go index d0a0330203..505fea1b2e 100644 --- a/logger/options.go +++ b/logger/options.go @@ -20,28 +20,28 @@ type Options struct { Context context.Context } -// WithFields set default fields for the logger +// WithFields set default fields for the logger. func WithFields(fields map[string]interface{}) Option { return func(args *Options) { args.Fields = fields } } -// WithLevel set default level for the logger +// WithLevel set default level for the logger. func WithLevel(level Level) Option { return func(args *Options) { args.Level = level } } -// WithOutput set default output writer for the logger +// WithOutput set default output writer for the logger. func WithOutput(out io.Writer) Option { return func(args *Options) { args.Out = out } } -// WithCallerSkipCount set frame count to skip +// WithCallerSkipCount set frame count to skip. func WithCallerSkipCount(c int) Option { return func(args *Options) { args.CallerSkipCount = c diff --git a/metadata/metadata.go b/metadata/metadata.go index 6fcb81996d..595b77ea05 100644 --- a/metadata/metadata.go +++ b/metadata/metadata.go @@ -36,7 +36,7 @@ func (md Metadata) Delete(key string) { delete(md, strings.Title(key)) } -// Copy makes a copy of the metadata +// Copy makes a copy of the metadata. func Copy(md Metadata) Metadata { cmd := make(Metadata, len(md)) for k, v := range md { @@ -45,12 +45,12 @@ func Copy(md Metadata) Metadata { return cmd } -// Delete key from metadata +// Delete key from metadata. func Delete(ctx context.Context, k string) context.Context { return Set(ctx, k, "") } -// Set add key with val to metadata +// Set add key with val to metadata. func Set(ctx context.Context, k, v string) context.Context { md, ok := FromContext(ctx) if !ok { @@ -64,7 +64,7 @@ func Set(ctx context.Context, k, v string) context.Context { return context.WithValue(ctx, metadataKey{}, md) } -// Get returns a single value from metadata in the context +// Get returns a single value from metadata in the context. func Get(ctx context.Context, key string) (string, bool) { md, ok := FromContext(ctx) if !ok { @@ -82,7 +82,7 @@ func Get(ctx context.Context, key string) (string, bool) { return val, ok } -// FromContext returns metadata from the given context +// FromContext returns metadata from the given context. func FromContext(ctx context.Context) (Metadata, bool) { md, ok := ctx.Value(metadataKey{}).(Metadata) if !ok { @@ -98,12 +98,12 @@ func FromContext(ctx context.Context) (Metadata, bool) { return newMD, ok } -// NewContext creates a new context with the given metadata +// NewContext creates a new context with the given metadata. func NewContext(ctx context.Context, md Metadata) context.Context { return context.WithValue(ctx, metadataKey{}, md) } -// MergeContext merges metadata to existing metadata, overwriting if specified +// MergeContext merges metadata to existing metadata, overwriting if specified. func MergeContext(ctx context.Context, patchMd Metadata, overwrite bool) context.Context { if ctx == nil { ctx = context.Background() diff --git a/metadata/metadata_test.go b/metadata/metadata_test.go index 6a3764b461..b893dc333a 100644 --- a/metadata/metadata_test.go +++ b/metadata/metadata_test.go @@ -36,7 +36,6 @@ func TestMetadataDelete(t *testing.T) { if ok { t.Fatal("key Baz not deleted") } - } func TestMetadataCopy(t *testing.T) { diff --git a/micro.go b/micro.go index b6fb707b99..8dfc0970a4 100644 --- a/micro.go +++ b/micro.go @@ -12,11 +12,11 @@ type serviceKey struct{} // Service is an interface that wraps the lower level libraries // within go-micro. Its a convenience method for building -// and initialising services. +// and initializing services. type Service interface { // The service name Name() string - // Init initialises options + // Init initializes options Init(...Option) // Options returns the current options Options() Options @@ -30,13 +30,13 @@ type Service interface { String() string } -// Event is used to publish messages to a topic +// Event is used to publish messages to a topic. type Event interface { // Publish publishes a message to the event topic Publish(ctx context.Context, msg interface{}, opts ...client.PublishOption) error } -// Type alias to satisfy the deprecation +// Type alias to satisfy the deprecation. type Publisher = Event type Option func(*Options) @@ -57,7 +57,7 @@ func NewContext(ctx context.Context, s Service) context.Context { return context.WithValue(ctx, serviceKey{}, s) } -// NewEvent creates a new event publisher +// NewEvent creates a new event publisher. func NewEvent(topic string, c client.Client) Event { if c == nil { c = client.NewClient() @@ -65,12 +65,12 @@ func NewEvent(topic string, c client.Client) Event { return &event{c, topic} } -// RegisterHandler is syntactic sugar for registering a handler +// RegisterHandler is syntactic sugar for registering a handler. func RegisterHandler(s server.Server, h interface{}, opts ...server.HandlerOption) error { return s.Handle(s.NewHandler(h, opts...)) } -// RegisterSubscriber is syntactic sugar for registering a subscriber +// RegisterSubscriber is syntactic sugar for registering a subscriber. func RegisterSubscriber(topic string, s server.Server, h interface{}, opts ...server.SubscriberOption) error { return s.Subscribe(s.NewSubscriber(topic, h, opts...)) } diff --git a/options.go b/options.go index 40f15aee1c..687351ce03 100644 --- a/options.go +++ b/options.go @@ -22,7 +22,7 @@ import ( "go-micro.dev/v4/util/cmd" ) -// Options for micro service +// Options for micro service. type Options struct { Auth auth.Auth Broker broker.Broker @@ -75,7 +75,7 @@ func newOptions(opts ...Option) Options { return opt } -// Broker to be used for service +// Broker to be used for service. func Broker(b broker.Broker) Option { return func(o *Options) { o.Broker = b @@ -97,7 +97,7 @@ func Cmd(c cmd.Cmd) Option { } } -// Client to be used for service +// Client to be used for service. func Client(c client.Client) Option { return func(o *Options) { o.Client = c @@ -121,21 +121,21 @@ func HandleSignal(b bool) Option { } } -// Profile to be used for debug profile +// Profile to be used for debug profile. func Profile(p profile.Profile) Option { return func(o *Options) { o.Profile = p } } -// Server to be used for service +// Server to be used for service. func Server(s server.Server) Option { return func(o *Options) { o.Server = s } } -// Store sets the store to use +// Store sets the store to use. func Store(s store.Store) Option { return func(o *Options) { o.Store = s @@ -143,7 +143,7 @@ func Store(s store.Store) Option { } // Registry sets the registry for the service -// and the underlying components +// and the underlying components. func Registry(r registry.Registry) Option { return func(o *Options) { o.Registry = r @@ -155,28 +155,28 @@ func Registry(r registry.Registry) Option { } } -// Tracer sets the tracer for the service +// Tracer sets the tracer for the service. func Tracer(t trace.Tracer) Option { return func(o *Options) { o.Server.Init(server.Tracer(t)) } } -// Auth sets the auth for the service +// Auth sets the auth for the service. func Auth(a auth.Auth) Option { return func(o *Options) { o.Auth = a } } -// Config sets the config for the service +// Config sets the config for the service. func Config(c config.Config) Option { return func(o *Options) { o.Config = c } } -// Selector sets the selector for the service client +// Selector sets the selector for the service client. func Selector(s selector.Selector) Option { return func(o *Options) { o.Client.Init(client.Selector(s)) @@ -184,7 +184,7 @@ func Selector(s selector.Selector) Option { } // Transport sets the transport for the service -// and the underlying components +// and the underlying components. func Transport(t transport.Transport) Option { return func(o *Options) { o.Transport = t @@ -194,7 +194,7 @@ func Transport(t transport.Transport) Option { } } -// Runtime sets the runtime +// Runtime sets the runtime. func Runtime(r runtime.Runtime) Option { return func(o *Options) { o.Runtime = r @@ -203,56 +203,56 @@ func Runtime(r runtime.Runtime) Option { // Convenience options -// Address sets the address of the server +// Address sets the address of the server. func Address(addr string) Option { return func(o *Options) { o.Server.Init(server.Address(addr)) } } -// Name of the service +// Name of the service. func Name(n string) Option { return func(o *Options) { o.Server.Init(server.Name(n)) } } -// Version of the service +// Version of the service. func Version(v string) Option { return func(o *Options) { o.Server.Init(server.Version(v)) } } -// Metadata associated with the service +// Metadata associated with the service. func Metadata(md map[string]string) Option { return func(o *Options) { o.Server.Init(server.Metadata(md)) } } -// Flags that can be passed to service +// Flags that can be passed to service. func Flags(flags ...cli.Flag) Option { return func(o *Options) { o.Cmd.App().Flags = append(o.Cmd.App().Flags, flags...) } } -// Action can be used to parse user provided cli options +// Action can be used to parse user provided cli options. func Action(a func(*cli.Context) error) Option { return func(o *Options) { o.Cmd.App().Action = a } } -// RegisterTTL specifies the TTL to use when registering the service +// RegisterTTL specifies the TTL to use when registering the service. func RegisterTTL(t time.Duration) Option { return func(o *Options) { o.Server.Init(server.RegisterTTL(t)) } } -// RegisterInterval specifies the interval on which to re-register +// RegisterInterval specifies the interval on which to re-register. func RegisterInterval(t time.Duration) Option { return func(o *Options) { o.Server.Init(server.RegisterInterval(t)) @@ -271,14 +271,14 @@ func WrapClient(w ...client.Wrapper) Option { } } -// WrapCall is a convenience method for wrapping a Client CallFunc +// WrapCall is a convenience method for wrapping a Client CallFunc. func WrapCall(w ...client.CallWrapper) Option { return func(o *Options) { o.Client.Init(client.WrapCall(w...)) } } -// WrapHandler adds a handler Wrapper to a list of options passed into the server +// WrapHandler adds a handler Wrapper to a list of options passed into the server. func WrapHandler(w ...server.HandlerWrapper) Option { return func(o *Options) { var wrappers []server.Option @@ -292,7 +292,7 @@ func WrapHandler(w ...server.HandlerWrapper) Option { } } -// WrapSubscriber adds a subscriber Wrapper to a list of options passed into the server +// WrapSubscriber adds a subscriber Wrapper to a list of options passed into the server. func WrapSubscriber(w ...server.SubscriberWrapper) Option { return func(o *Options) { var wrappers []server.Option @@ -306,7 +306,7 @@ func WrapSubscriber(w ...server.SubscriberWrapper) Option { } } -// Add opt to server option +// Add opt to server option. func AddListenOption(option server.Option) Option { return func(o *Options) { o.Server.Init(option) @@ -315,35 +315,35 @@ func AddListenOption(option server.Option) Option { // Before and Afters -// BeforeStart run funcs before service starts +// BeforeStart run funcs before service starts. func BeforeStart(fn func() error) Option { return func(o *Options) { o.BeforeStart = append(o.BeforeStart, fn) } } -// BeforeStop run funcs before service stops +// BeforeStop run funcs before service stops. func BeforeStop(fn func() error) Option { return func(o *Options) { o.BeforeStop = append(o.BeforeStop, fn) } } -// AfterStart run funcs after service starts +// AfterStart run funcs after service starts. func AfterStart(fn func() error) Option { return func(o *Options) { o.AfterStart = append(o.AfterStart, fn) } } -// AfterStop run funcs after service stops +// AfterStop run funcs after service stops. func AfterStop(fn func() error) Option { return func(o *Options) { o.AfterStop = append(o.AfterStop, fn) } } -// Logger sets the logger for the service +// Logger sets the logger for the service. func Logger(l logger.Logger) Option { return func(o *Options) { o.Logger = l diff --git a/registry/cache/cache.go b/registry/cache/cache.go index 5d17d02040..a6b92b0bdf 100644 --- a/registry/cache/cache.go +++ b/registry/cache/cache.go @@ -14,7 +14,7 @@ import ( util "go-micro.dev/v4/util/registry" ) -// Cache is the registry cache interface +// Cache is the registry cache interface. type Cache interface { // embed the registry interface registry.Registry @@ -77,7 +77,7 @@ func (c *cache) setStatus(err error) { c.Unlock() } -// isValid checks if the service is valid +// isValid checks if the service is valid. func (c *cache) isValid(services []*registry.Service, ttl time.Time) bool { // no services exist if len(services) == 0 { @@ -318,7 +318,7 @@ func (c *cache) update(res *registry.Result) { } // run starts the cache watcher loop -// it creates a new watcher if there's a problem +// it creates a new watcher if there's a problem. func (c *cache) run(service string) { c.Lock() c.watchedRunning[service] = true @@ -394,7 +394,7 @@ func (c *cache) run(service string) { } // watch loops the next event and calls update -// it returns if there's an error +// it returns if there's an error. func (c *cache) watch(w registry.Watcher) error { // used to stop the watch stop := make(chan bool) @@ -462,7 +462,7 @@ func (c *cache) String() string { return "cache" } -// New returns a new cache +// New returns a new cache. func New(r registry.Registry, opts ...Option) Cache { rand.Seed(time.Now().UnixNano()) options := Options{ diff --git a/registry/cache/options.go b/registry/cache/options.go index 90681972d6..38f26dc18b 100644 --- a/registry/cache/options.go +++ b/registry/cache/options.go @@ -6,14 +6,14 @@ import ( "go-micro.dev/v4/logger" ) -// WithTTL sets the cache TTL +// WithTTL sets the cache TTL. func WithTTL(t time.Duration) Option { return func(o *Options) { o.TTL = t } } -// WithLogger sets the underline logger +// WithLogger sets the underline logger. func WithLogger(l logger.Logger) Option { return func(o *Options) { o.Logger = l diff --git a/registry/mdns_registry.go b/registry/mdns_registry.go index ef51e7c2d5..dfdf8f5930 100644 --- a/registry/mdns_registry.go +++ b/registry/mdns_registry.go @@ -22,7 +22,7 @@ import ( ) var ( - // use a .micro domain rather than .local + // use a .micro domain rather than .local. mdnsDomain = "micro" ) @@ -517,7 +517,6 @@ func (m *mdnsRegistry) Watch(opts ...WatchOption) (Watcher, error) { m.mtx.RUnlock() } } - }() // start listening, blocking call @@ -614,7 +613,7 @@ func (m *mdnsWatcher) Stop() { } } -// NewRegistry returns a new default registry which is mdns +// NewRegistry returns a new default registry which is mdns. func NewRegistry(opts ...Option) Registry { return newRegistry(opts...) } diff --git a/registry/mdns_test.go b/registry/mdns_test.go index a7b17fc446..de5a6bcab5 100644 --- a/registry/mdns_test.go +++ b/registry/mdns_test.go @@ -92,7 +92,6 @@ func TestMDNS(t *testing.T) { if len(s) != 1 { t.Fatalf("Expected one result for %s got %d", service.Name, len(s)) - } if s[0].Name != service.Name { @@ -148,7 +147,6 @@ func TestMDNS(t *testing.T) { t.Fatalf("Expected nothing got %+v", s[0]) } } - } func TestEncoding(t *testing.T) { @@ -208,7 +206,6 @@ func TestEncoding(t *testing.T) { } } } - } func TestWatcher(t *testing.T) { @@ -274,7 +271,6 @@ func TestWatcher(t *testing.T) { testFn := func(service, s *Service) { if s == nil { t.Fatalf("Expected one result for %s got nil", service.Name) - } if s.Name != service.Name { diff --git a/registry/options.go b/registry/options.go index d2c3990167..38359d89a9 100644 --- a/registry/options.go +++ b/registry/options.go @@ -60,7 +60,7 @@ func NewOptions(opts ...Option) *Options { return &options } -// Addrs is the registry addresses to use +// Addrs is the registry addresses to use. func Addrs(addrs ...string) Option { return func(o *Options) { o.Addrs = addrs @@ -73,14 +73,14 @@ func Timeout(t time.Duration) Option { } } -// Secure communication with the registry +// Secure communication with the registry. func Secure(b bool) Option { return func(o *Options) { o.Secure = b } } -// Specify TLS Config +// Specify TLS Config. func TLSConfig(t *tls.Config) Option { return func(o *Options) { o.TLSConfig = t @@ -99,7 +99,7 @@ func RegisterContext(ctx context.Context) RegisterOption { } } -// Watch a service +// Watch a service. func WatchService(name string) WatchOption { return func(o *WatchOptions) { o.Service = name @@ -153,7 +153,7 @@ func getServiceRecords(ctx context.Context) map[string]map[string]*record { return services } -// Services is an option that preloads service data +// Services is an option that preloads service data. func Services(s map[string][]*Service) Option { return func(o *Options) { if o.Context == nil { @@ -163,7 +163,7 @@ func Services(s map[string][]*Service) Option { } } -// Logger sets the underline logger +// Logger sets the underline logger. func Logger(l logger.Logger) Option { return func(o *Options) { o.Logger = l diff --git a/registry/registry.go b/registry/registry.go index dce9b43134..f27d3be2b0 100644 --- a/registry/registry.go +++ b/registry/registry.go @@ -8,15 +8,15 @@ import ( var ( DefaultRegistry = NewRegistry() - // Not found error when GetService is called + // Not found error when GetService is called. ErrNotFound = errors.New("service not found") - // Watcher stopped error when watcher is stopped + // Watcher stopped error when watcher is stopped. ErrWatcherStopped = errors.New("watcher stopped") ) // The registry provides an interface for service discovery // and an abstraction over varying implementations -// {consul, etcd, zookeeper, ...} +// {consul, etcd, zookeeper, ...}. type Registry interface { Init(...Option) error Options() Options @@ -72,7 +72,7 @@ func Register(s *Service, opts ...RegisterOption) error { return DefaultRegistry.Register(s, opts...) } -// Deregister a service node +// Deregister a service node. func Deregister(s *Service) error { return DefaultRegistry.Deregister(s) } @@ -82,7 +82,7 @@ func GetService(name string) ([]*Service, error) { return DefaultRegistry.GetService(name) } -// List the services. Only returns service names +// List the services. Only returns service names. func ListServices() ([]*Service, error) { return DefaultRegistry.ListServices() } diff --git a/registry/watcher.go b/registry/watcher.go index 33289e1b3b..c9d073ed27 100644 --- a/registry/watcher.go +++ b/registry/watcher.go @@ -11,25 +11,25 @@ type Watcher interface { } // Result is returned by a call to Next on -// the watcher. Actions can be create, update, delete +// the watcher. Actions can be create, update, delete. type Result struct { Action string Service *Service } -// EventType defines registry event type +// EventType defines registry event type. type EventType int const ( - // Create is emitted when a new service is registered + // Create is emitted when a new service is registered. Create EventType = iota - // Delete is emitted when an existing service is deregsitered + // Delete is emitted when an existing service is deregsitered. Delete - // Update is emitted when an existing servicec is updated + // Update is emitted when an existing servicec is updated. Update ) -// String returns human readable event type +// String returns human readable event type. func (t EventType) String() string { switch t { case Create: @@ -43,7 +43,7 @@ func (t EventType) String() string { } } -// Event is registry event +// Event is registry event. type Event struct { // Id is registry id Id string diff --git a/runtime/default.go b/runtime/default.go index d1a5f51f5f..614a3a1a4a 100644 --- a/runtime/default.go +++ b/runtime/default.go @@ -18,7 +18,7 @@ import ( "go-micro.dev/v4/runtime/local/git" ) -// defaultNamespace to use if not provided as an option +// defaultNamespace to use if not provided as an option. const defaultNamespace = "default" type runtime struct { @@ -36,7 +36,7 @@ type runtime struct { namespaces map[string]map[string]*service } -// NewRuntime creates new local runtime and returns it +// NewRuntime creates new local runtime and returns it. func NewRuntime(opts ...Option) Runtime { // get default options options := NewOptions(opts...) @@ -53,7 +53,7 @@ func NewRuntime(opts ...Option) Runtime { } } -// @todo move this to runtime default +// @todo move this to runtime default. func (r *runtime) checkoutSourceIfNeeded(s *Service) error { // Runtime service like config have no source. // Skip checkout in that case @@ -131,7 +131,6 @@ func uncompress(src string, dst string) error { // check the type switch header.Typeflag { - // if its a dir and it doesn't exist create it (with 0755 permission) case tar.TypeDir: if _, err := os.Stat(target); err != nil { @@ -162,7 +161,7 @@ func uncompress(src string, dst string) error { return nil } -// check for path traversal and correct forward slashes +// check for path traversal and correct forward slashes. func validRelPath(p string) bool { if p == "" || strings.Contains(p, `\`) || strings.HasPrefix(p, "/") || strings.Contains(p, "../") { return false @@ -170,7 +169,7 @@ func validRelPath(p string) bool { return true } -// Init initializes runtime options +// Init initializes runtime options. func (r *runtime) Init(opts ...Option) error { r.Lock() defer r.Unlock() @@ -182,7 +181,7 @@ func (r *runtime) Init(opts ...Option) error { return nil } -// run runs the runtime management loop +// run runs the runtime management loop. func (r *runtime) run(events <-chan Event) { t := time.NewTicker(time.Second * 5) defer t.Stop() @@ -306,7 +305,7 @@ func serviceKey(s *Service) string { return fmt.Sprintf("%v:%v", s.Name, s.Version) } -// Create creates a new service which is then started by runtime +// Create creates a new service which is then started by runtime. func (r *runtime) Create(s *Service, opts ...CreateOption) error { err := r.checkoutSourceIfNeeded(s) if err != nil { @@ -357,7 +356,7 @@ func (r *runtime) Create(s *Service, opts ...CreateOption) error { return nil } -// exists returns whether the given file or directory exists +// exists returns whether the given file or directory exists. func exists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { @@ -431,7 +430,6 @@ func (r *runtime) Logs(s *Service, options ...LogsOption) (LogStream, error) { return } } - }() return ret, nil } @@ -516,7 +514,7 @@ func (r *runtime) Read(opts ...ReadOption) ([]*Service, error) { return services, nil } -// Update attempts to update the service +// Update attempts to update the service. func (r *runtime) Update(s *Service, opts ...UpdateOption) error { var options UpdateOptions for _, o := range opts { @@ -553,7 +551,7 @@ func (r *runtime) Update(s *Service, opts ...UpdateOption) error { return service.Start() } -// Delete removes the service from the runtime and stops it +// Delete removes the service from the runtime and stops it. func (r *runtime) Delete(s *Service, opts ...DeleteOption) error { r.Lock() defer r.Unlock() @@ -594,7 +592,7 @@ func (r *runtime) Delete(s *Service, opts ...DeleteOption) error { return nil } -// Start starts the runtime +// Start starts the runtime. func (r *runtime) Start() error { r.Lock() defer r.Unlock() @@ -623,7 +621,7 @@ func (r *runtime) Start() error { return nil } -// Stop stops the runtime +// Stop stops the runtime. func (r *runtime) Stop() error { r.Lock() defer r.Unlock() @@ -658,7 +656,7 @@ func (r *runtime) Stop() error { return nil } -// String implements stringer interface +// String implements stringer interface. func (r *runtime) String() string { return "local" } diff --git a/runtime/kubernetes/kubernetes.go b/runtime/kubernetes/kubernetes.go index 1dde9af27d..8b9fa2815b 100644 --- a/runtime/kubernetes/kubernetes.go +++ b/runtime/kubernetes/kubernetes.go @@ -11,7 +11,7 @@ import ( "go-micro.dev/v4/util/kubernetes/client" ) -// action to take on runtime service +// action to take on runtime service. type action int type kubernetes struct { @@ -28,7 +28,7 @@ type kubernetes struct { namespaces []client.Namespace } -// namespaceExists returns a boolean indicating if a namespace exists +// namespaceExists returns a boolean indicating if a namespace exists. func (k *kubernetes) namespaceExists(name string) (bool, error) { // populate the cache if k.namespaces == nil { @@ -50,7 +50,7 @@ func (k *kubernetes) namespaceExists(name string) (bool, error) { return false, nil } -// createNamespace creates a new k8s namespace +// createNamespace creates a new k8s namespace. func (k *kubernetes) createNamespace(namespace string) error { ns := client.Namespace{Metadata: &client.Metadata{Name: namespace}} err := k.client.Create(&client.Resource{Kind: "namespace", Value: ns}) @@ -64,7 +64,7 @@ func (k *kubernetes) createNamespace(namespace string) error { } // getService queries kubernetes for micro service -// NOTE: this function is not thread-safe +// NOTE: this function is not thread-safe. func (k *kubernetes) getService(labels map[string]string, opts ...client.GetOption) ([]*service, error) { // get the service status serviceList := new(client.ServiceList) @@ -231,7 +231,7 @@ func (k *kubernetes) getService(labels map[string]string, opts ...client.GetOpti return services, nil } -// run runs the runtime management loop +// run runs the runtime management loop. func (k *kubernetes) run(events <-chan runtime.Event) { t := time.NewTicker(time.Second * 10) defer t.Stop() @@ -308,7 +308,7 @@ func (k *kubernetes) run(events <-chan runtime.Event) { } } -// Init initializes runtime options +// Init initializes runtime options. func (k *kubernetes) Init(opts ...runtime.Option) error { k.Lock() defer k.Unlock() @@ -375,7 +375,7 @@ func (k *kubeStream) Stop() error { return nil } -// Creates a service +// Creates a service. func (k *kubernetes) Create(s *runtime.Service, opts ...runtime.CreateOption) error { k.Lock() defer k.Unlock() @@ -421,7 +421,7 @@ func (k *kubernetes) Create(s *runtime.Service, opts ...runtime.CreateOption) er return service.Start(k.client, client.CreateNamespace(options.Namespace)) } -// Read returns all instances of given service +// Read returns all instances of given service. func (k *kubernetes) Read(opts ...runtime.ReadOption) ([]*runtime.Service, error) { k.Lock() defer k.Unlock() @@ -463,7 +463,7 @@ func (k *kubernetes) Read(opts ...runtime.ReadOption) ([]*runtime.Service, error return services, nil } -// Update the service in place +// Update the service in place. func (k *kubernetes) Update(s *runtime.Service, opts ...runtime.UpdateOption) error { options := runtime.UpdateOptions{ Namespace: client.DefaultNamespace, @@ -515,7 +515,7 @@ func (k *kubernetes) Update(s *runtime.Service, opts ...runtime.UpdateOption) er return nil } -// Delete removes a service +// Delete removes a service. func (k *kubernetes) Delete(s *runtime.Service, opts ...runtime.DeleteOption) error { options := runtime.DeleteOptions{ Namespace: client.DefaultNamespace, @@ -537,7 +537,7 @@ func (k *kubernetes) Delete(s *runtime.Service, opts ...runtime.DeleteOption) er return service.Stop(k.client, client.DeleteNamespace(options.Namespace)) } -// Start starts the runtime +// Start starts the runtime. func (k *kubernetes) Start() error { k.Lock() defer k.Unlock() @@ -566,7 +566,7 @@ func (k *kubernetes) Start() error { return nil } -// Stop shuts down the runtime +// Stop shuts down the runtime. func (k *kubernetes) Stop() error { k.Lock() defer k.Unlock() @@ -591,12 +591,12 @@ func (k *kubernetes) Stop() error { return nil } -// String implements stringer interface +// String implements stringer interface. func (k *kubernetes) String() string { return "kubernetes" } -// NewRuntime creates new kubernetes runtime +// NewRuntime creates new kubernetes runtime. func NewRuntime(opts ...runtime.Option) runtime.Runtime { // get default options // Create labels with type "micro": "service" diff --git a/runtime/kubernetes/logs.go b/runtime/kubernetes/logs.go index b1cb471a28..c7c81314d9 100644 --- a/runtime/kubernetes/logs.go +++ b/runtime/kubernetes/logs.go @@ -9,9 +9,9 @@ import ( "strconv" "time" + "go-micro.dev/v4/logger" "go-micro.dev/v4/runtime" "go-micro.dev/v4/util/kubernetes/client" - "go-micro.dev/v4/util/log" ) type klog struct { @@ -37,7 +37,11 @@ func (k *klog) podLogStream(podName string, stream *kubeStream) error { if err != nil { stream.err = err - stream.Stop() + if err := stream.Stop(); err != nil { + stream.err = err + return err + } + return err } @@ -86,7 +90,12 @@ func (k *klog) getMatchingPods() ([]string, error) { var matches []string - for _, p := range r.Value.(*client.PodList).Items { + podList, ok := r.Value.(*client.PodList) + if !ok { + logger.DefaultLogger.Log(logger.ErrorLevel, "Failed to cast to *client.PodList") + } + + for _, p := range podList.Items { // find labels that match the name if p.Metadata.Labels["name"] == client.Format(k.serviceName) { matches = append(matches, p.Metadata.Name) @@ -107,7 +116,7 @@ func (k *klog) Read() ([]runtime.LogRecord, error) { for _, pod := range pods { logParams := make(map[string]string) - //if !opts.Since.Equal(time.Time{}) { + // if !opts.Since.Equal(time.Time{}) { // logParams["sinceSeconds"] = strconv.Itoa(int(time.Since(opts.Since).Seconds())) //} @@ -168,7 +177,7 @@ func (k *klog) Stream() (runtime.LogStream, error) { go func(podName string) { err := k.podLogStream(podName, stream) if err != nil { - log.Errorf("Error streaming from pod: %v", err) + logger.DefaultLogger.Log(logger.ErrorLevel, err) } }(pod) } @@ -176,7 +185,7 @@ func (k *klog) Stream() (runtime.LogStream, error) { return stream, nil } -// NewLog returns a configured Kubernetes logger +// NewLog returns a configured Kubernetes logger. func newLog(c client.Client, serviceName string, opts ...runtime.LogsOption) *klog { options := runtime.LogsOptions{ Namespace: client.DefaultNamespace, diff --git a/runtime/kubernetes/service.go b/runtime/kubernetes/service.go index 5d4864b9c3..dbefbc300b 100644 --- a/runtime/kubernetes/service.go +++ b/runtime/kubernetes/service.go @@ -115,7 +115,7 @@ func serviceResource(s *client.Service) *client.Resource { } } -// Start starts the Kubernetes service. It creates new kubernetes deployment and service API objects +// Start starts the Kubernetes service. It creates new kubernetes deployment and service API objects. func (s *service) Start(k client.Client, opts ...client.CreateOption) error { // create deployment first; if we fail, we dont create service if err := k.Create(deploymentResource(s.kdeploy), opts...); err != nil { diff --git a/runtime/local/build/build.go b/runtime/local/build/build.go index 8241c2769a..bbc9e335f2 100644 --- a/runtime/local/build/build.go +++ b/runtime/local/build/build.go @@ -5,7 +5,7 @@ import ( "go-micro.dev/v4/runtime/local/source" ) -// Builder builds binaries +// Builder builds binaries. type Builder interface { // Build builds a package Build(*Source) (*Package, error) @@ -13,7 +13,7 @@ type Builder interface { Clean(*Package) error } -// Source is the source of a build +// Source is the source of a build. type Source struct { // Language is the language of code Language string @@ -21,7 +21,7 @@ type Source struct { Repository *source.Repository } -// Package is micro service package +// Package is micro service package. type Package struct { // Name of the binary Name string diff --git a/runtime/local/build/go/golang.go b/runtime/local/build/go/golang.go index 7b3337c6c5..92f63f0ae0 100644 --- a/runtime/local/build/go/golang.go +++ b/runtime/local/build/go/golang.go @@ -15,7 +15,7 @@ type Builder struct { Path string } -// whichGo locates the go command +// whichGo locates the go command. func whichGo() string { // check GOROOT if gr := os.Getenv("GOROOT"); len(gr) > 0 { diff --git a/runtime/local/build/options.go b/runtime/local/build/options.go index 65e7dd68c2..c6a01aecc3 100644 --- a/runtime/local/build/options.go +++ b/runtime/local/build/options.go @@ -7,7 +7,7 @@ type Options struct { type Option func(o *Options) -// Local path for repository +// Local path for repository. func Path(p string) Option { return func(o *Options) { o.Path = p diff --git a/runtime/local/git/git.go b/runtime/local/git/git.go index 246aa79cc7..2c034144d8 100644 --- a/runtime/local/git/git.go +++ b/runtime/local/git/git.go @@ -165,7 +165,7 @@ func dirifyRepo(s string) string { return s } -// exists returns whether the given file or directory exists +// exists returns whether the given file or directory exists. func pathExists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { @@ -178,7 +178,7 @@ func pathExists(path string) (bool, error) { } // GetRepoRoot determines the repo root from a full path. -// Returns empty string and no error if not found +// Returns empty string and no error if not found. func GetRepoRoot(fullPath string) (string, error) { // traverse parent directories prev := fullPath @@ -203,7 +203,7 @@ func GetRepoRoot(fullPath string) (string, error) { const defaultRepo = "github.com/micro/services" -// Source is not just git related @todo move +// Source is not just git related @todo move. type Source struct { // is it a local folder intended for a local runtime? Local bool diff --git a/runtime/local/local.go b/runtime/local/local.go index ce9f535d22..f8f10b2064 100644 --- a/runtime/local/local.go +++ b/runtime/local/local.go @@ -5,7 +5,7 @@ import ( "go-micro.dev/v4/runtime" ) -// NewRuntime returns a new local runtime +// NewRuntime returns a new local runtime. func NewRuntime(opts ...runtime.Option) runtime.Runtime { return runtime.NewRuntime(opts...) } diff --git a/runtime/local/process/os/os.go b/runtime/local/process/os/os.go index ff38f49779..e540a79fc4 100644 --- a/runtime/local/process/os/os.go +++ b/runtime/local/process/os/os.go @@ -21,7 +21,6 @@ func (p *Process) Exec(exe *process.Executable) error { } func (p *Process) Fork(exe *process.Executable) (*process.PID, error) { - // create command cmd := exec.Command(exe.Package.Path, exe.Args...) diff --git a/runtime/local/process/process.go b/runtime/local/process/process.go index fb718c9860..65e901cff2 100644 --- a/runtime/local/process/process.go +++ b/runtime/local/process/process.go @@ -7,7 +7,7 @@ import ( "go-micro.dev/v4/runtime/local/build" ) -// Process manages a running process +// Process manages a running process. type Process interface { // Executes a process to completion Exec(*Executable) error @@ -30,7 +30,7 @@ type Executable struct { Dir string } -// PID is the running process +// PID is the running process. type PID struct { // ID of the process ID string diff --git a/runtime/local/source/git/git.go b/runtime/local/source/git/git.go index f46cccf603..74f90a284a 100644 --- a/runtime/local/source/git/git.go +++ b/runtime/local/source/git/git.go @@ -11,7 +11,7 @@ import ( ) // Source retrieves source code -// An empty struct can be used +// An empty struct can be used. type Source struct { Options source.Options } diff --git a/runtime/local/source/go/golang.go b/runtime/local/source/go/golang.go index e01c80062f..a7a535efc7 100644 --- a/runtime/local/source/go/golang.go +++ b/runtime/local/source/go/golang.go @@ -41,7 +41,7 @@ func (g *Source) Fetch(url string) (*source.Repository, error) { }, nil } -// Commit is not yet supported +// Commit is not yet supported. func (g *Source) Commit(r *source.Repository) error { return nil } @@ -50,7 +50,7 @@ func (g *Source) String() string { return "golang" } -// whichGo locates the go command +// whichGo locates the go command. func whichGo() string { // check GOROOT if gr := os.Getenv("GOROOT"); len(gr) > 0 { diff --git a/runtime/local/source/options.go b/runtime/local/source/options.go index 2e842f33f0..637ebda952 100644 --- a/runtime/local/source/options.go +++ b/runtime/local/source/options.go @@ -7,7 +7,7 @@ type Options struct { type Option func(o *Options) -// Local path for repository +// Local path for repository. func Path(p string) Option { return func(o *Options) { o.Path = p diff --git a/runtime/local/source/source.go b/runtime/local/source/source.go index 2afa92e378..41467b6c50 100644 --- a/runtime/local/source/source.go +++ b/runtime/local/source/source.go @@ -1,7 +1,7 @@ // Package source retrieves source code package source -// Source retrieves source code +// Source retrieves source code. type Source interface { // Fetch repo from a url Fetch(url string) (*Repository, error) @@ -11,7 +11,7 @@ type Source interface { String() string } -// Repository is the source repository +// Repository is the source repository. type Repository struct { // Name or repo Name string diff --git a/runtime/options.go b/runtime/options.go index e196bd01a2..a33683bac0 100644 --- a/runtime/options.go +++ b/runtime/options.go @@ -10,7 +10,7 @@ import ( type Option func(o *Options) -// Options configure runtime +// Options configure runtime. type Options struct { // Scheduler for updates Scheduler Scheduler @@ -38,42 +38,42 @@ func NewOptions(opts ...Option) *Options { return options } -// WithSource sets the base image / repository +// WithSource sets the base image / repository. func WithSource(src string) Option { return func(o *Options) { o.Source = src } } -// WithScheduler specifies a scheduler for updates +// WithScheduler specifies a scheduler for updates. func WithScheduler(n Scheduler) Option { return func(o *Options) { o.Scheduler = n } } -// WithType sets the service type to manage +// WithType sets the service type to manage. func WithType(t string) Option { return func(o *Options) { o.Type = t } } -// WithImage sets the image to use +// WithImage sets the image to use. func WithImage(t string) Option { return func(o *Options) { o.Image = t } } -// WithClient sets the client to use +// WithClient sets the client to use. func WithClient(c client.Client) Option { return func(o *Options) { o.Client = c } } -// WithLogger sets the underline logger +// WithLogger sets the underline logger. func WithLogger(l logger.Logger) Option { return func(o *Options) { o.Logger = l @@ -84,7 +84,7 @@ type CreateOption func(o *CreateOptions) type ReadOption func(o *ReadOptions) -// CreateOptions configure runtime services +// CreateOptions configure runtime services. type CreateOptions struct { // Command to execut Command []string @@ -106,7 +106,7 @@ type CreateOptions struct { Context context.Context } -// ReadOptions queries runtime services +// ReadOptions queries runtime services. type ReadOptions struct { // Service name Service string @@ -120,35 +120,35 @@ type ReadOptions struct { Context context.Context } -// CreateType sets the type of service to create +// CreateType sets the type of service to create. func CreateType(t string) CreateOption { return func(o *CreateOptions) { o.Type = t } } -// CreateImage sets the image to use +// CreateImage sets the image to use. func CreateImage(img string) CreateOption { return func(o *CreateOptions) { o.Image = img } } -// CreateNamespace sets the namespace +// CreateNamespace sets the namespace. func CreateNamespace(ns string) CreateOption { return func(o *CreateOptions) { o.Namespace = ns } } -// CreateContext sets the context +// CreateContext sets the context. func CreateContext(ctx context.Context) CreateOption { return func(o *CreateOptions) { o.Context = ctx } } -// WithCommand specifies the command to execute +// WithCommand specifies the command to execute. func WithCommand(cmd ...string) CreateOption { return func(o *CreateOptions) { // set command @@ -156,7 +156,7 @@ func WithCommand(cmd ...string) CreateOption { } } -// WithArgs specifies the command to execute +// WithArgs specifies the command to execute. func WithArgs(args ...string) CreateOption { return func(o *CreateOptions) { // set command @@ -164,56 +164,55 @@ func WithArgs(args ...string) CreateOption { } } -// WithRetries sets the max retries attemps func WithRetries(retries int) CreateOption { return func(o *CreateOptions) { o.Retries = retries } } -// WithEnv sets the created service environment +// WithEnv sets the created service environment. func WithEnv(env []string) CreateOption { return func(o *CreateOptions) { o.Env = env } } -// WithOutput sets the arg output +// WithOutput sets the arg output. func WithOutput(out io.Writer) CreateOption { return func(o *CreateOptions) { o.Output = out } } -// ReadService returns services with the given name +// ReadService returns services with the given name. func ReadService(service string) ReadOption { return func(o *ReadOptions) { o.Service = service } } -// ReadVersion confifgures service version +// ReadVersion confifgures service version. func ReadVersion(version string) ReadOption { return func(o *ReadOptions) { o.Version = version } } -// ReadType returns services of the given type +// ReadType returns services of the given type. func ReadType(t string) ReadOption { return func(o *ReadOptions) { o.Type = t } } -// ReadNamespace sets the namespace +// ReadNamespace sets the namespace. func ReadNamespace(ns string) ReadOption { return func(o *ReadOptions) { o.Namespace = ns } } -// ReadContext sets the context +// ReadContext sets the context. func ReadContext(ctx context.Context) ReadOption { return func(o *ReadOptions) { o.Context = ctx @@ -229,14 +228,14 @@ type UpdateOptions struct { Context context.Context } -// UpdateNamespace sets the namespace +// UpdateNamespace sets the namespace. func UpdateNamespace(ns string) UpdateOption { return func(o *UpdateOptions) { o.Namespace = ns } } -// UpdateContext sets the context +// UpdateContext sets the context. func UpdateContext(ctx context.Context) UpdateOption { return func(o *UpdateOptions) { o.Context = ctx @@ -252,24 +251,24 @@ type DeleteOptions struct { Context context.Context } -// DeleteNamespace sets the namespace +// DeleteNamespace sets the namespace. func DeleteNamespace(ns string) DeleteOption { return func(o *DeleteOptions) { o.Namespace = ns } } -// DeleteContext sets the context +// DeleteContext sets the context. func DeleteContext(ctx context.Context) DeleteOption { return func(o *DeleteOptions) { o.Context = ctx } } -// LogsOption configures runtime logging +// LogsOption configures runtime logging. type LogsOption func(o *LogsOptions) -// LogsOptions configure runtime logging +// LogsOptions configure runtime logging. type LogsOptions struct { // How many existing lines to show Count int64 @@ -281,28 +280,28 @@ type LogsOptions struct { Context context.Context } -// LogsExistingCount confiures how many existing lines to show +// LogsExistingCount confiures how many existing lines to show. func LogsCount(count int64) LogsOption { return func(l *LogsOptions) { l.Count = count } } -// LogsStream configures whether to stream new lines +// LogsStream configures whether to stream new lines. func LogsStream(stream bool) LogsOption { return func(l *LogsOptions) { l.Stream = stream } } -// LogsNamespace sets the namespace +// LogsNamespace sets the namespace. func LogsNamespace(ns string) LogsOption { return func(o *LogsOptions) { o.Namespace = ns } } -// LogsContext sets the context +// LogsContext sets the context. func LogsContext(ctx context.Context) LogsOption { return func(o *LogsOptions) { o.Context = ctx diff --git a/runtime/runtime.go b/runtime/runtime.go index 1299baf526..f54ca5429a 100644 --- a/runtime/runtime.go +++ b/runtime/runtime.go @@ -7,15 +7,15 @@ import ( ) var ( - // DefaultRuntime is default micro runtime + // DefaultRuntime is default micro runtime. DefaultRuntime Runtime = NewRuntime() - // DefaultName is default runtime service name + // DefaultName is default runtime service name. DefaultName = "go.micro.runtime" ErrAlreadyExists = errors.New("already exists") ) -// Runtime is a service runtime manager +// Runtime is a service runtime manager. type Runtime interface { // Init initializes runtime Init(...Option) error @@ -37,7 +37,7 @@ type Runtime interface { String() string } -// Stream returns a log stream +// Stream returns a log stream. type LogStream interface { Error() error Chan() chan LogRecord @@ -49,7 +49,7 @@ type LogRecord struct { Metadata map[string]string } -// Scheduler is a runtime service scheduler +// Scheduler is a runtime service scheduler. type Scheduler interface { // Notify publishes schedule events Notify() (<-chan Event, error) @@ -57,19 +57,19 @@ type Scheduler interface { Close() error } -// EventType defines schedule event +// EventType defines schedule event. type EventType int const ( - // Create is emitted when a new build has been craeted + // Create is emitted when a new build has been craeted. Create EventType = iota - // Update is emitted when a new update become available + // Update is emitted when a new update become available. Update - // Delete is emitted when a build has been deleted + // Delete is emitted when a build has been deleted. Delete ) -// String returns human readable event type +// String returns human readable event type. func (t EventType) String() string { switch t { case Create: @@ -83,7 +83,7 @@ func (t EventType) String() string { } } -// Event is notification event +// Event is notification event. type Event struct { // ID of the event ID string @@ -97,7 +97,7 @@ type Event struct { Options *CreateOptions } -// Service is runtime service +// Service is runtime service. type Service struct { // Name of the service Name string diff --git a/runtime/service.go b/runtime/service.go index 4134066391..2be41a8b2b 100644 --- a/runtime/service.go +++ b/runtime/service.go @@ -96,7 +96,7 @@ func (s *service) Running() bool { return s.running } -// Start starts the service +// Start starts the service. func (s *service) Start() error { s.Lock() defer s.Unlock() @@ -141,7 +141,7 @@ func (s *service) Start() error { return nil } -// Status updates the status of the service. Assumes it's called under a lock as it mutates state +// Status updates the status of the service. Assumes it's called under a lock as it mutates state. func (s *service) Status(status string, err error) { s.Metadata["lastStatusUpdate"] = time.Now().Format(time.RFC3339) s.Metadata["status"] = status @@ -150,10 +150,9 @@ func (s *service) Status(status string, err error) { return } s.Metadata["error"] = err.Error() - } -// Stop stops the service +// Stop stops the service. func (s *service) Stop() error { s.Lock() defer s.Unlock() @@ -187,14 +186,14 @@ func (s *service) Stop() error { } } -// Error returns the last error service has returned +// Error returns the last error service has returned. func (s *service) Error() error { s.RLock() defer s.RUnlock() return s.err } -// Wait waits for the service to finish running +// Wait waits for the service to finish running. func (s *service) Wait() { // wait for process to exit s.RLock() diff --git a/selector/common_test.go b/selector/common_test.go index 1fe797e1d6..c2e947c924 100644 --- a/selector/common_test.go +++ b/selector/common_test.go @@ -5,7 +5,7 @@ import ( ) var ( - // mock data + // mock data. testData = map[string][]*registry.Service{ "foo": { { diff --git a/selector/default.go b/selector/default.go index fa8aebf232..1e07beaec9 100644 --- a/selector/default.go +++ b/selector/default.go @@ -76,7 +76,7 @@ func (c *registrySelector) Mark(service string, node *registry.Node, err error) func (c *registrySelector) Reset(service string) { } -// Close stops the watcher and destroys the cache +// Close stops the watcher and destroys the cache. func (c *registrySelector) Close() error { c.rc.Stop() diff --git a/selector/options.go b/selector/options.go index 5f844aed9c..bea8ff2ba2 100644 --- a/selector/options.go +++ b/selector/options.go @@ -27,20 +27,19 @@ type SelectOptions struct { Context context.Context } -// Option used to initialise the selector type Option func(*Options) -// SelectOption used when making a select call +// SelectOption used when making a select call. type SelectOption func(*SelectOptions) -// Registry sets the registry used by the selector +// Registry sets the registry used by the selector. func Registry(r registry.Registry) Option { return func(o *Options) { o.Registry = r } } -// SetStrategy sets the default strategy for the selector +// SetStrategy sets the default strategy for the selector. func SetStrategy(fn Strategy) Option { return func(o *Options) { o.Strategy = fn @@ -55,14 +54,14 @@ func WithFilter(fn ...Filter) SelectOption { } } -// Strategy sets the selector strategy +// Strategy sets the selector strategy. func WithStrategy(fn Strategy) SelectOption { return func(o *SelectOptions) { o.Strategy = fn } } -// WithLogger sets the underline logger +// WithLogger sets the underline logger. func WithLogger(l logger.Logger) Option { return func(o *Options) { o.Logger = l diff --git a/selector/selector.go b/selector/selector.go index 4391d7298d..acd031e03f 100644 --- a/selector/selector.go +++ b/selector/selector.go @@ -26,13 +26,13 @@ type Selector interface { } // Next is a function that returns the next node -// based on the selector's strategy +// based on the selector's strategy. type Next func() (*registry.Node, error) -// Filter is used to filter a service during the selection process +// Filter is used to filter a service during the selection process. type Filter func([]*registry.Service) []*registry.Service -// Strategy is a selection strategy e.g random, round robin +// Strategy is a selection strategy e.g random, round robin. type Strategy func([]*registry.Service) Next var ( diff --git a/selector/strategy.go b/selector/strategy.go index e42a3e4243..4253483b86 100644 --- a/selector/strategy.go +++ b/selector/strategy.go @@ -12,7 +12,7 @@ func init() { rand.Seed(time.Now().UnixNano()) } -// Random is a random strategy algorithm for node selection +// Random is a random strategy algorithm for node selection. func Random(services []*registry.Service) Next { nodes := make([]*registry.Node, 0, len(services)) @@ -30,7 +30,7 @@ func Random(services []*registry.Service) Next { } } -// RoundRobin is a roundrobin strategy algorithm for node selection +// RoundRobin is a roundrobin strategy algorithm for node selection. func RoundRobin(services []*registry.Service) Next { nodes := make([]*registry.Node, 0, len(services)) diff --git a/server/extractor_test.go b/server/extractor_test.go index f650d64ec9..e97c1b653b 100644 --- a/server/extractor_test.go +++ b/server/extractor_test.go @@ -61,5 +61,4 @@ func TestExtractEndpoint(t *testing.T) { if endpoints[0].Response.Type != "testResponse" { t.Errorf("Expected testResponse type got %s", endpoints[0].Response.Type) } - } diff --git a/server/handler.go b/server/handler.go index 8236c355e5..1209643425 100644 --- a/server/handler.go +++ b/server/handler.go @@ -30,7 +30,7 @@ func EndpointMetadata(name string, md map[string]string) HandlerOption { // Internal Handler options specifies that a handler is not advertised // to the discovery system. In the future this may also limit request -// to the internal network or authorised user. +// to the internal network or authorized user. func InternalHandler(b bool) HandlerOption { return func(o *HandlerOptions) { o.Internal = b @@ -65,14 +65,14 @@ func DisableAutoAck() SubscriberOption { } } -// Shared queue name distributed messages across subscribers +// Shared queue name distributed messages across subscribers. func SubscriberQueue(n string) SubscriberOption { return func(o *SubscriberOptions) { o.Queue = n } } -// SubscriberContext set context options to allow broker SubscriberOption passed +// SubscriberContext set context options to allow broker SubscriberOption passed. func SubscriberContext(ctx context.Context) SubscriberOption { return func(o *SubscriberOptions) { o.Context = ctx diff --git a/server/options.go b/server/options.go index 631145a31f..8290dced60 100644 --- a/server/options.go +++ b/server/options.go @@ -32,7 +32,7 @@ func newRouterOptions(opt ...RouterOption) RouterOptions { return opts } -// WithRouterLogger sets the underline router logger +// WithRouterLogger sets the underline router logger. func WithRouterLogger(l logger.Logger) RouterOption { return func(o *RouterOptions) { o.Logger = l @@ -122,49 +122,49 @@ func newOptions(opt ...Option) Options { return opts } -// Server name +// Server name. func Name(n string) Option { return func(o *Options) { o.Name = n } } -// Unique server id +// Unique server id. func Id(id string) Option { return func(o *Options) { o.Id = id } } -// Version of the service +// Version of the service. func Version(v string) Option { return func(o *Options) { o.Version = v } } -// Address to bind to - host:port +// Address to bind to - host:port. func Address(a string) Option { return func(o *Options) { o.Address = a } } -// The address to advertise for discovery - host:port +// The address to advertise for discovery - host:port. func Advertise(a string) Option { return func(o *Options) { o.Advertise = a } } -// Broker to use for pub/sub +// Broker to use for pub/sub. func Broker(b broker.Broker) Option { return func(o *Options) { o.Broker = b } } -// Codec to use to encode/decode requests for a given content type +// Codec to use to encode/decode requests for a given content type. func Codec(contentType string, c codec.NewCodec) Option { return func(o *Options) { o.Codecs[contentType] = c @@ -180,56 +180,56 @@ func Context(ctx context.Context) Option { } } -// Registry used for discovery +// Registry used for discovery. func Registry(r registry.Registry) Option { return func(o *Options) { o.Registry = r } } -// Tracer mechanism for distributed tracking +// Tracer mechanism for distributed tracking. func Tracer(t trace.Tracer) Option { return func(o *Options) { o.Tracer = t } } -// Transport mechanism for communication e.g http, rabbitmq, etc +// Transport mechanism for communication e.g http, rabbitmq, etc. func Transport(t transport.Transport) Option { return func(o *Options) { o.Transport = t } } -// Metadata associated with the server +// Metadata associated with the server. func Metadata(md map[string]string) Option { return func(o *Options) { o.Metadata = md } } -// RegisterCheck run func before registry service +// RegisterCheck run func before registry service. func RegisterCheck(fn func(context.Context) error) Option { return func(o *Options) { o.RegisterCheck = fn } } -// Register the service with a TTL +// Register the service with a TTL. func RegisterTTL(t time.Duration) Option { return func(o *Options) { o.RegisterTTL = t } } -// Register the service with at interval +// Register the service with at interval. func RegisterInterval(t time.Duration) Option { return func(o *Options) { o.RegisterInterval = t } } -// TLSConfig specifies a *tls.Config +// TLSConfig specifies a *tls.Config. func TLSConfig(t *tls.Config) Option { return func(o *Options) { // set the internal tls @@ -249,14 +249,14 @@ func TLSConfig(t *tls.Config) Option { } } -// WithRouter sets the request router +// WithRouter sets the request router. func WithRouter(r Router) Option { return func(o *Options) { o.Router = r } } -// WithLogger sets the underline logger +// WithLogger sets the underline logger. func WithLogger(l logger.Logger) Option { return func(o *Options) { o.Logger = l @@ -279,14 +279,14 @@ func Wait(wg *sync.WaitGroup) Option { } } -// Adds a handler Wrapper to a list of options passed into the server +// Adds a handler Wrapper to a list of options passed into the server. func WrapHandler(w HandlerWrapper) Option { return func(o *Options) { o.HdlrWrappers = append(o.HdlrWrappers, w) } } -// Adds a subscriber Wrapper to a list of options passed into the server +// Adds a subscriber Wrapper to a list of options passed into the server. func WrapSubscriber(w SubscriberWrapper) Option { return func(o *Options) { o.SubWrappers = append(o.SubWrappers, w) @@ -294,7 +294,7 @@ func WrapSubscriber(w SubscriberWrapper) Option { } // Add transport.ListenOption to the ListenOptions list, when using it, it will be passed to the -// httpTransport.Listen() method +// httpTransport.Listen() method. func ListenOption(option transport.ListenOption) Option { return func(o *Options) { o.ListenOptions = append(o.ListenOptions, option) diff --git a/server/rpc_codec.go b/server/rpc_codec.go index 78fee60704..5c81faa1c6 100644 --- a/server/rpc_codec.go +++ b/server/rpc_codec.go @@ -49,7 +49,7 @@ var ( "application/octet-stream": raw.NewCodec, } - // TODO: remove legacy codec list + // TODO: remove legacy codec list. defaultCodecs = map[string]codec.NewCodec{ "application/json": jsonrpc.NewCodec, "application/json-rpc": jsonrpc.NewCodec, @@ -58,7 +58,7 @@ var ( "application/octet-stream": protorpc.NewCodec, } - // the local buffer pool + // the local buffer pool. bufferPool = bpool.NewSizedBufferPool(32, 1) ) @@ -122,7 +122,7 @@ func setHeaders(m, r *codec.Message) { set("Micro-Error", r.Error) } -// setupProtocol sets up the old protocol +// setupProtocol sets up the old protocol. func setupProtocol(msg *transport.Message) codec.NewCodec { service := getHeader("Micro-Service", msg.Header) method := getHeader("Micro-Method", msg.Header) diff --git a/server/rpc_codec_test.go b/server/rpc_codec_test.go index c853902768..4c228c4300 100644 --- a/server/rpc_codec_test.go +++ b/server/rpc_codec_test.go @@ -9,7 +9,7 @@ import ( "go-micro.dev/v4/transport" ) -// testCodec is a dummy codec that only knows how to encode nil bodies +// testCodec is a dummy codec that only knows how to encode nil bodies. type testCodec struct { buf *bytes.Buffer } diff --git a/server/rpc_event.go b/server/rpc_event.go index 674bf9dc83..b724930880 100644 --- a/server/rpc_event.go +++ b/server/rpc_event.go @@ -5,7 +5,7 @@ import ( "go-micro.dev/v4/transport" ) -// event is a broker event we handle on the server transport +// event is a broker event we handle on the server transport. type event struct { err error message *broker.Message diff --git a/server/rpc_router.go b/server/rpc_router.go index a195c8f251..5c788f0950 100644 --- a/server/rpc_router.go +++ b/server/rpc_router.go @@ -81,7 +81,7 @@ type router struct { subscribers map[string][]*subscriber } -// rpcRouter encapsulates functions that become a server.Router +// rpcRouter encapsulates functions that become a server.Router. type rpcRouter struct { h func(context.Context, Request, interface{}) error m func(context.Context, Message) error @@ -570,7 +570,7 @@ func (router *router) ProcessMessage(ctx context.Context, msg Message) (err erro return err } - // create the handler which will honour the SubscriberFunc type + // create the handler which will honor the SubscriberFunc type fn := func(ctx context.Context, msg Message) error { var vals []reflect.Value if sub.typ.Kind() != reflect.Func { diff --git a/server/rpc_server.go b/server/rpc_server.go index 5aba1459fd..30f609c4c3 100644 --- a/server/rpc_server.go +++ b/server/rpc_server.go @@ -130,7 +130,7 @@ func (s *rpcServer) HandleEvent(e broker.Event) error { return r.ProcessMessage(ctx, rpcMsg) } -// ServeConn serves a single connection +// ServeConn serves a single connection. func (s *rpcServer) ServeConn(sock transport.Socket) { logger := s.opts.Logger // global error tracking diff --git a/server/rpc_stream.go b/server/rpc_stream.go index 1778de0c20..760f6dcda3 100644 --- a/server/rpc_stream.go +++ b/server/rpc_stream.go @@ -9,7 +9,7 @@ import ( "go-micro.dev/v4/codec" ) -// Implements the Streamer interface +// Implements the Streamer interface. type rpcStream struct { sync.RWMutex id string diff --git a/server/rpc_stream_test.go b/server/rpc_stream_test.go index f90bda7071..7f034efea3 100644 --- a/server/rpc_stream_test.go +++ b/server/rpc_stream_test.go @@ -14,7 +14,7 @@ import ( protoCodec "go-micro.dev/v4/codec/proto" ) -// protoStruct implements proto.Message +// protoStruct implements proto.Message. type protoStruct struct { Payload string `protobuf:"bytes,1,opt,name=service,proto3" json:"service,omitempty"` } @@ -23,7 +23,7 @@ func (m *protoStruct) Reset() { *m = protoStruct{} } func (m *protoStruct) String() string { return proto.CompactTextString(m) } func (*protoStruct) ProtoMessage() {} -// safeBuffer throws away everything and wont Read data back +// safeBuffer throws away everything and wont Read data back. type safeBuffer struct { sync.RWMutex buf []byte diff --git a/server/rpc_util.go b/server/rpc_util.go index a15be0acdc..454edc1ede 100644 --- a/server/rpc_util.go +++ b/server/rpc_util.go @@ -4,7 +4,7 @@ import ( "sync" ) -// waitgroup for global management of connections +// waitgroup for global management of connections. type waitGroup struct { // local waitgroup lg sync.WaitGroup diff --git a/server/server.go b/server/server.go index e838c92502..bddc19dd14 100644 --- a/server/server.go +++ b/server/server.go @@ -15,9 +15,9 @@ import ( signalutil "go-micro.dev/v4/util/signal" ) -// Server is a simple micro server abstraction +// Server is a simple micro server abstraction. type Server interface { - // Initialise options + // Initialize options Init(...Option) error // Retrieve the options Options() Options @@ -37,7 +37,7 @@ type Server interface { String() string } -// Router handle serving messages +// Router handle serving messages. type Router interface { // ProcessMessage processes a message ProcessMessage(context.Context, Message) error @@ -45,7 +45,7 @@ type Router interface { ServeRequest(context.Context, Request, Response) error } -// Message is an async message interface +// Message is an async message interface. type Message interface { // Topic of the message Topic() string @@ -61,7 +61,7 @@ type Message interface { Codec() codec.Reader } -// Request is a synchronous request interface +// Request is a synchronous request interface. type Request interface { // Service name requested Service() string @@ -83,7 +83,7 @@ type Request interface { Stream() bool } -// Response is the response writer for unencoded messages +// Response is the response writer for unencoded messages. type Response interface { // Encoded writer Codec() codec.Writer @@ -126,7 +126,7 @@ type Handler interface { // Subscriber interface represents a subscription to a given topic using // a specific subscriber function or object with endpoints. It mirrors -// the handler in its behaviour. +// the handler in its behavior. type Subscriber interface { Topic() string Subscriber() interface{} @@ -147,16 +147,15 @@ var ( DefaultRegisterInterval = time.Second * 30 DefaultRegisterTTL = time.Second * 90 - // NewServer creates a new server + // NewServer creates a new server. NewServer func(...Option) Server = newRpcServer ) -// DefaultOptions returns config options for the default service +// DefaultOptions returns config options for the default service. func DefaultOptions() Options { return DefaultServer.Options() } -// Init initialises the default server with options passed in func Init(opt ...Option) { if DefaultServer == nil { DefaultServer = newRpcServer(opt...) @@ -164,13 +163,13 @@ func Init(opt ...Option) { DefaultServer.Init(opt...) } -// NewRouter returns a new router +// NewRouter returns a new router. func NewRouter() *router { return newRpcRouter() } // NewSubscriber creates a new subscriber interface with the given topic -// and handler using the default server +// and handler using the default server. func NewSubscriber(topic string, h interface{}, opts ...SubscriberOption) Subscriber { return DefaultServer.NewSubscriber(topic, h, opts...) } @@ -189,19 +188,19 @@ func NewHandler(h interface{}, opts ...HandlerOption) Handler { } // Handle registers a handler interface with the default server to -// handle inbound requests +// handle inbound requests. func Handle(h Handler) error { return DefaultServer.Handle(h) } // Subscribe registers a subscriber interface with the default server -// which subscribes to specified topic with the broker +// which subscribes to specified topic with the broker. func Subscribe(s Subscriber) error { return DefaultServer.Subscribe(s) } // Run starts the default server and waits for a kill -// signal before exiting. Also registers/deregisters the server +// signal before exiting. Also registers/deregisters the server. func Run() error { if err := Start(); err != nil { return err @@ -214,20 +213,20 @@ func Run() error { return Stop() } -// Start starts the default server +// Start starts the default server. func Start() error { config := DefaultServer.Options() config.Logger.Logf(log.InfoLevel, "Starting server %s id %s", config.Name, config.Id) return DefaultServer.Start() } -// Stop stops the default server +// Stop stops the default server. func Stop() error { DefaultServer.Options().Logger.Logf(log.InfoLevel, "Stopping server") return DefaultServer.Stop() } -// String returns name of Server implementation +// String returns name of Server implementation. func String() string { return DefaultServer.String() } diff --git a/server/wrapper.go b/server/wrapper.go index 3e4d3ecd12..cf12efcd58 100644 --- a/server/wrapper.go +++ b/server/wrapper.go @@ -14,10 +14,10 @@ type HandlerFunc func(ctx context.Context, req Request, rsp interface{}) error // publication message. type SubscriberFunc func(ctx context.Context, msg Message) error -// HandlerWrapper wraps the HandlerFunc and returns the equivalent +// HandlerWrapper wraps the HandlerFunc and returns the equivalent. type HandlerWrapper func(HandlerFunc) HandlerFunc -// SubscriberWrapper wraps the SubscriberFunc and returns the equivalent +// SubscriberWrapper wraps the SubscriberFunc and returns the equivalent. type SubscriberWrapper func(SubscriberFunc) SubscriberFunc // StreamWrapper wraps a Stream interface and returns the equivalent. diff --git a/service.go b/service.go index 5aa4d0f96d..7cfdec801a 100644 --- a/service.go +++ b/service.go @@ -30,7 +30,7 @@ func (s *service) Name() string { return s.opts.Server.Options().Name } -// Init initialises options. Additionally it calls cmd.Init +// Init initializes options. Additionally it calls cmd.Init // which parses command line flags. cmd.Init is only called // on first Init. func (s *service) Init(opts ...Option) { @@ -45,7 +45,7 @@ func (s *service) Init(opts ...Option) { s.opts.Cmd.App().Name = s.Server().Options().Name } - // Initialise the command flags, overriding new service + // Initialize the command flags, overriding new service if err := s.opts.Cmd.Init( cmd.Auth(&s.opts.Auth), cmd.Broker(&s.opts.Broker), diff --git a/service_test.go b/service_test.go index cf779a5fcc..39ad42b4ea 100644 --- a/service_test.go +++ b/service_test.go @@ -25,7 +25,7 @@ func testShutdown(wg *sync.WaitGroup, cancel func()) { wg.Wait() } -func testService(ctx context.Context, wg *sync.WaitGroup, name string) Service { +func testService(t testing.TB, ctx context.Context, wg *sync.WaitGroup, name string) Service { // add self wg.Add(1) @@ -38,15 +38,19 @@ func testService(ctx context.Context, wg *sync.WaitGroup, name string) Service { Registry(r), AfterStart(func() error { wg.Done() + return nil }), AfterStop(func() error { wg.Done() + return nil }), ) - RegisterHandler(srv.Server(), handler.NewHandler(srv.Client())) + if err := RegisterHandler(srv.Server(), handler.NewHandler(srv.Client())); err != nil { + t.Fatal(err) + } return srv } @@ -101,7 +105,7 @@ func testRequest(ctx context.Context, c client.Client, name string) error { return nil } -// TestService tests running and calling a service +// TestService tests running and calling a service. func TestService(t *testing.T) { // waitgroup for server start var wg sync.WaitGroup @@ -110,7 +114,7 @@ func TestService(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) // start test server - service := testService(ctx, &wg, "test.service") + service := testService(t, ctx, &wg, "test.service") go func() { // wait for service to start @@ -132,7 +136,6 @@ func TestService(t *testing.T) { } func benchmarkCustomListenService(b *testing.B, n int, name string) { - // create custom listen customListen, err := net.Listen("tcp", server.DefaultAddress) if err != nil { @@ -208,7 +211,7 @@ func benchmarkService(b *testing.B, n int, name string) { ctx, cancel := context.WithCancel(context.Background()) // create test server - service := testService(ctx, &wg, name) + service := testService(b, ctx, &wg, name) // start the server go func() { @@ -238,7 +241,9 @@ func benchmarkService(b *testing.B, n int, name string) { go func() { err := testRequest(ctx, service.Client(), name) + wg.Done() + if err != nil { b.Fatal(err) } diff --git a/store/memory.go b/store/memory.go index 3b1481f100..6c14da957d 100644 --- a/store/memory.go +++ b/store/memory.go @@ -10,7 +10,7 @@ import ( "github.com/pkg/errors" ) -// NewMemoryStore returns a memory store +// NewMemoryStore returns a memory store. func NewMemoryStore(opts ...Option) Store { s := &memoryStore{ options: Options{ diff --git a/store/options.go b/store/options.go index a10ddf71d4..ed07c69018 100644 --- a/store/options.go +++ b/store/options.go @@ -8,7 +8,7 @@ import ( "go-micro.dev/v4/logger" ) -// Options contains configuration for the Store +// Options contains configuration for the Store. type Options struct { // Nodes contains the addresses or other connection information of the backing storage. // For example, an etcd implementation would contain the nodes of the cluster. @@ -16,7 +16,7 @@ type Options struct { Nodes []string // Database allows multiple isolated stores to be kept in one backend, if supported. Database string - // Table is analagous to a table in database backends or a key prefix in KV backends + // Table is analogous to a table in database backends or a key prefix in KV backends Table string // Context should contain all implementation specific options, using context.WithValue. Context context.Context @@ -26,7 +26,7 @@ type Options struct { Logger logger.Logger } -// Option sets values in Options +// Option sets values in Options. type Option func(o *Options) // Nodes contains the addresses or other connection information of the backing storage. @@ -45,35 +45,34 @@ func Database(db string) Option { } } -// Table is analagous to a table in database backends or a key prefix in KV backends func Table(t string) Option { return func(o *Options) { o.Table = t } } -// WithContext sets the stores context, for any extra configuration +// WithContext sets the stores context, for any extra configuration. func WithContext(c context.Context) Option { return func(o *Options) { o.Context = c } } -// WithClient sets the stores client to use for RPC +// WithClient sets the stores client to use for RPC. func WithClient(c client.Client) Option { return func(o *Options) { o.Client = c } } -// WithLogger sets the underline logger +// WithLogger sets the underline logger. func WithLogger(l logger.Logger) Option { return func(o *Options) { o.Logger = l } } -// ReadOptions configures an individual Read operation +// ReadOptions configures an individual Read operation. type ReadOptions struct { Database, Table string // Prefix returns all records that are prefixed with key @@ -86,10 +85,10 @@ type ReadOptions struct { Offset uint } -// ReadOption sets values in ReadOptions +// ReadOption sets values in ReadOptions. type ReadOption func(r *ReadOptions) -// ReadFrom the database and table +// ReadFrom the database and table. func ReadFrom(database, table string) ReadOption { return func(r *ReadOptions) { r.Database = database @@ -97,28 +96,28 @@ func ReadFrom(database, table string) ReadOption { } } -// ReadPrefix returns all records that are prefixed with key +// ReadPrefix returns all records that are prefixed with key. func ReadPrefix() ReadOption { return func(r *ReadOptions) { r.Prefix = true } } -// ReadSuffix returns all records that have the suffix key +// ReadSuffix returns all records that have the suffix key. func ReadSuffix() ReadOption { return func(r *ReadOptions) { r.Suffix = true } } -// ReadLimit limits the number of responses to l +// ReadLimit limits the number of responses to l. func ReadLimit(l uint) ReadOption { return func(r *ReadOptions) { r.Limit = l } } -// ReadOffset starts returning responses from o. Use in conjunction with Limit for pagination +// ReadOffset starts returning responses from o. Use in conjunction with Limit for pagination. func ReadOffset(o uint) ReadOption { return func(r *ReadOptions) { r.Offset = o @@ -126,7 +125,7 @@ func ReadOffset(o uint) ReadOption { } // WriteOptions configures an individual Write operation -// If Expiry and TTL are set TTL takes precedence +// If Expiry and TTL are set TTL takes precedence. type WriteOptions struct { Database, Table string // Expiry is the time the record expires @@ -135,10 +134,10 @@ type WriteOptions struct { TTL time.Duration } -// WriteOption sets values in WriteOptions +// WriteOption sets values in WriteOptions. type WriteOption func(w *WriteOptions) -// WriteTo the database and table +// WriteTo the database and table. func WriteTo(database, table string) WriteOption { return func(w *WriteOptions) { w.Database = database @@ -146,29 +145,29 @@ func WriteTo(database, table string) WriteOption { } } -// WriteExpiry is the time the record expires +// WriteExpiry is the time the record expires. func WriteExpiry(t time.Time) WriteOption { return func(w *WriteOptions) { w.Expiry = t } } -// WriteTTL is the time the record expires +// WriteTTL is the time the record expires. func WriteTTL(d time.Duration) WriteOption { return func(w *WriteOptions) { w.TTL = d } } -// DeleteOptions configures an individual Delete operation +// DeleteOptions configures an individual Delete operation. type DeleteOptions struct { Database, Table string } -// DeleteOption sets values in DeleteOptions +// DeleteOption sets values in DeleteOptions. type DeleteOption func(d *DeleteOptions) -// DeleteFrom the database and table +// DeleteFrom the database and table. func DeleteFrom(database, table string) DeleteOption { return func(d *DeleteOptions) { d.Database = database @@ -176,7 +175,7 @@ func DeleteFrom(database, table string) DeleteOption { } } -// ListOptions configures an individual List operation +// ListOptions configures an individual List operation. type ListOptions struct { // List from the following Database, Table string @@ -190,10 +189,10 @@ type ListOptions struct { Offset uint } -// ListOption sets values in ListOptions +// ListOption sets values in ListOptions. type ListOption func(l *ListOptions) -// ListFrom the database and table +// ListFrom the database and table. func ListFrom(database, table string) ListOption { return func(l *ListOptions) { l.Database = database @@ -201,21 +200,21 @@ func ListFrom(database, table string) ListOption { } } -// ListPrefix returns all keys that are prefixed with key +// ListPrefix returns all keys that are prefixed with key. func ListPrefix(p string) ListOption { return func(l *ListOptions) { l.Prefix = p } } -// ListSuffix returns all keys that end with key +// ListSuffix returns all keys that end with key. func ListSuffix(s string) ListOption { return func(l *ListOptions) { l.Suffix = s } } -// ListLimit limits the number of returned keys to l +// ListLimit limits the number of returned keys to l. func ListLimit(l uint) ListOption { return func(lo *ListOptions) { lo.Limit = l diff --git a/store/store.go b/store/store.go index d46b7b7a00..babe5b0ef7 100644 --- a/store/store.go +++ b/store/store.go @@ -8,15 +8,15 @@ import ( ) var ( - // ErrNotFound is returned when a key doesn't exist + // ErrNotFound is returned when a key doesn't exist. ErrNotFound = errors.New("not found") // DefaultStore is the memory store. DefaultStore Store = NewStore() ) -// Store is a data storage interface +// Store is a data storage interface. type Store interface { - // Init initialises the store. It must perform any required setup on the backing storage implementation and check that it is ready for use, returning any errors. + // Init initializes the store. It must perform any required setup on the backing storage implementation and check that it is ready for use, returning any errors. Init(...Option) error // Options allows you to view the current options. Options() Options @@ -34,7 +34,7 @@ type Store interface { String() string } -// Record is an item stored or retrieved from a Store +// Record is an item stored or retrieved from a Store. type Record struct { // The key to store the record Key string `json:"key"` diff --git a/sync/options.go b/sync/options.go index e318212583..a59535cf32 100644 --- a/sync/options.go +++ b/sync/options.go @@ -8,49 +8,49 @@ import ( "go-micro.dev/v4/logger" ) -// Nodes sets the addresses to use +// Nodes sets the addresses to use. func Nodes(a ...string) Option { return func(o *Options) { o.Nodes = a } } -// Prefix sets a prefix to any lock ids used +// Prefix sets a prefix to any lock ids used. func Prefix(p string) Option { return func(o *Options) { o.Prefix = p } } -// LockTTL sets the lock ttl +// LockTTL sets the lock ttl. func LockTTL(t time.Duration) LockOption { return func(o *LockOptions) { o.TTL = t } } -// LockWait sets the wait time +// LockWait sets the wait time. func LockWait(t time.Duration) LockOption { return func(o *LockOptions) { o.Wait = t } } -// WithTLS sets the TLS config +// WithTLS sets the TLS config. func WithTLS(t *tls.Config) Option { return func(o *Options) { o.TLSConfig = t } } -// WithContext sets the syncs context, for any extra configuration +// WithContext sets the syncs context, for any extra configuration. func WithContext(c context.Context) Option { return func(o *Options) { o.Context = c } } -// WithLogger sets the underline logger +// WithLogger sets the underline logger. func WithLogger(l logger.Logger) Option { return func(o *Options) { o.Logger = l diff --git a/sync/sync.go b/sync/sync.go index 25d19fe981..38a8994b3c 100644 --- a/sync/sync.go +++ b/sync/sync.go @@ -14,9 +14,9 @@ var ( ErrLockTimeout = errors.New("lock timeout") ) -// Sync is an interface for distributed synchronization +// Sync is an interface for distributed synchronization. type Sync interface { - // Initialise options + // Initialize options Init(...Option) error // Return the options Options() Options @@ -30,7 +30,7 @@ type Sync interface { String() string } -// Leader provides leadership election +// Leader provides leadership election. type Leader interface { // resign leadership Resign() error diff --git a/transport/context.go b/transport/context.go index 6886e26c6d..facbac5a44 100644 --- a/transport/context.go +++ b/transport/context.go @@ -6,7 +6,7 @@ import ( type netListener struct{} -// getNetListener Get net.Listener from ListenOptions +// getNetListener Get net.Listener from ListenOptions. func getNetListener(o *ListenOptions) net.Listener { if o.Context == nil { return nil diff --git a/transport/http_proxy.go b/transport/http_proxy.go index 567dd739a0..070fe76c6c 100644 --- a/transport/http_proxy.go +++ b/transport/http_proxy.go @@ -76,7 +76,7 @@ func proxyDial(conn net.Conn, addr string, proxyURL *url.URL) (_ net.Conn, err e return &pbuffer{Conn: conn, r: br}, nil } -// Creates a new connection +// Creates a new connection. func newConn(dial func(string) (net.Conn, error)) func(string) (net.Conn, error) { return func(addr string) (net.Conn, error) { // get the proxy url diff --git a/transport/http_transport.go b/transport/http_transport.go index 4629157ac2..7368acd517 100644 --- a/transport/http_transport.go +++ b/transport/http_transport.go @@ -563,7 +563,6 @@ func (h *httpTransport) Listen(addr string, opts ...ListenOption) (Listener, err var err error if listener := getNetListener(&options); listener != nil { - fn := func(addr string) (net.Listener, error) { return listener, nil } diff --git a/transport/memory_test.go b/transport/memory_test.go index 460b31115b..18ff2af2cc 100644 --- a/transport/memory_test.go +++ b/transport/memory_test.go @@ -59,7 +59,6 @@ func TestMemoryTransport(t *testing.T) { t.Logf("Client Received %s", string(m.Body)) } } - } func TestListener(t *testing.T) { diff --git a/transport/options.go b/transport/options.go index d20f10b9a3..dd1aff0b6c 100644 --- a/transport/options.go +++ b/transport/options.go @@ -39,7 +39,7 @@ type DialOptions struct { // Timeout for dialing Timeout time.Duration - // TODO: add tls options when dialling + // TODO: add tls options when dialing // Currently set in global options // Other options for implementations of the interface @@ -56,7 +56,7 @@ type ListenOptions struct { Context context.Context } -// Addrs to use for transport +// Addrs to use for transport. func Addrs(addrs ...string) Option { return func(o *Options) { o.Addrs = addrs @@ -64,14 +64,14 @@ func Addrs(addrs ...string) Option { } // Codec sets the codec used for encoding where the transport -// does not support message headers +// does not support message headers. func Codec(c codec.Marshaler) Option { return func(o *Options) { o.Codec = c } } -// Timeout sets the timeout for Send/Recv execution +// Timeout sets the timeout for Send/Recv execution. func Timeout(t time.Duration) Option { return func(o *Options) { o.Timeout = t @@ -79,7 +79,7 @@ func Timeout(t time.Duration) Option { } // Use secure communication. If TLSConfig is not specified we -// use InsecureSkipVerify and generate a self signed cert +// use InsecureSkipVerify and generate a self signed cert. func Secure(b bool) Option { return func(o *Options) { o.Secure = b @@ -93,28 +93,27 @@ func TLSConfig(t *tls.Config) Option { } } -// Indicates whether this is a streaming connection +// Indicates whether this is a streaming connection. func WithStream() DialOption { return func(o *DialOptions) { o.Stream = true } } -// Timeout used when dialling the remote side func WithTimeout(d time.Duration) DialOption { return func(o *DialOptions) { o.Timeout = d } } -// WithLogger sets the underline logger +// WithLogger sets the underline logger. func WithLogger(l logger.Logger) Option { return func(o *Options) { o.Logger = l } } -// NetListener Set net.Listener for httpTransport +// NetListener Set net.Listener for httpTransport. func NetListener(customListener net.Listener) ListenOption { return func(o *ListenOptions) { if customListener == nil { diff --git a/util/addr/addr.go b/util/addr/addr.go index d814a95c57..52427f38cc 100644 --- a/util/addr/addr.go +++ b/util/addr/addr.go @@ -17,7 +17,7 @@ func init() { } } -// AppendPrivateBlocks append private network blocks +// AppendPrivateBlocks append private network blocks. func AppendPrivateBlocks(bs ...string) { for _, b := range bs { if _, block, err := net.ParseCIDR(b); err == nil { @@ -36,7 +36,7 @@ func isPrivateIP(ipAddr string) bool { return false } -// IsLocal tells us whether an ip is local +// IsLocal tells us whether an ip is local. func IsLocal(addr string) bool { // extract the host host, _, err := net.SplitHostPort(addr) @@ -59,7 +59,7 @@ func IsLocal(addr string) bool { return false } -// Extract returns a real ip +// Extract returns a real ip. func Extract(addr string) (string, error) { // if addr specified then its returned if len(addr) > 0 && (addr != "0.0.0.0" && addr != "[::]" && addr != "::") { @@ -71,7 +71,6 @@ func Extract(addr string) (string, error) { return "", fmt.Errorf("Failed to get interfaces! Err: %v", err) } - //nolint:prealloc var addrs []net.Addr var loAddrs []net.Addr for _, iface := range ifaces { @@ -132,7 +131,7 @@ func Extract(addr string) (string, error) { return "", fmt.Errorf("No IP address found, and explicit IP not provided") } -// IPs returns all known ips +// IPs returns all known ips. func IPs() []string { ifaces, err := net.Interfaces() if err != nil { diff --git a/util/addr/addr_test.go b/util/addr/addr_test.go index e728552b34..29cde02d4e 100644 --- a/util/addr/addr_test.go +++ b/util/addr/addr_test.go @@ -49,12 +49,10 @@ func TestExtractor(t *testing.T) { if ip == nil { t.Error("Unexpected nil IP") } - } else if addr != d.expect { t.Errorf("Expected %s got %s", d.expect, addr) } } - } func TestAppendPrivateBlocks(t *testing.T) { diff --git a/util/cmd/cmd.go b/util/cmd/cmd.go index 96f3aea343..70d4c6a305 100644 --- a/util/cmd/cmd.go +++ b/util/cmd/cmd.go @@ -29,7 +29,7 @@ import ( type Cmd interface { // The cli app within this cmd App() *cli.App - // Adds options, parses flags and initialise + // Adds options, parses flags and initialize // exits on error Init(opts ...Option) error // Options set within this command diff --git a/util/cmd/options.go b/util/cmd/options.go index 8ed3a29b10..68a784a1c6 100644 --- a/util/cmd/options.go +++ b/util/cmd/options.go @@ -58,21 +58,21 @@ type Options struct { Context context.Context } -// Command line Name +// Command line Name. func Name(n string) Option { return func(o *Options) { o.Name = n } } -// Command line Description +// Command line Description. func Description(d string) Option { return func(o *Options) { o.Description = d } } -// Command line Version +// Command line Version. func Version(v string) Option { return func(o *Options) { o.Version = v @@ -157,84 +157,84 @@ func Profile(p *profile.Profile) Option { } } -// New broker func +// New broker func. func NewBroker(name string, b func(...broker.Option) broker.Broker) Option { return func(o *Options) { o.Brokers[name] = b } } -// New cache func +// New cache func. func NewCache(name string, c func(...cache.Option) cache.Cache) Option { return func(o *Options) { o.Caches[name] = c } } -// New client func +// New client func. func NewClient(name string, b func(...client.Option) client.Client) Option { return func(o *Options) { o.Clients[name] = b } } -// New registry func +// New registry func. func NewRegistry(name string, r func(...registry.Option) registry.Registry) Option { return func(o *Options) { o.Registries[name] = r } } -// New selector func +// New selector func. func NewSelector(name string, s func(...selector.Option) selector.Selector) Option { return func(o *Options) { o.Selectors[name] = s } } -// New server func +// New server func. func NewServer(name string, s func(...server.Option) server.Server) Option { return func(o *Options) { o.Servers[name] = s } } -// New transport func +// New transport func. func NewTransport(name string, t func(...transport.Option) transport.Transport) Option { return func(o *Options) { o.Transports[name] = t } } -// New runtime func +// New runtime func. func NewRuntime(name string, r func(...runtime.Option) runtime.Runtime) Option { return func(o *Options) { o.Runtimes[name] = r } } -// New tracer func +// New tracer func. func NewTracer(name string, t func(...trace.Option) trace.Tracer) Option { return func(o *Options) { o.Tracers[name] = t } } -// New auth func +// New auth func. func NewAuth(name string, t func(...auth.Option) auth.Auth) Option { return func(o *Options) { o.Auths[name] = t } } -// New config func +// New config func. func NewConfig(name string, t func(...config.Option) (config.Config, error)) Option { return func(o *Options) { o.Configs[name] = t } } -// New profile func +// New profile func. func NewProfile(name string, t func(...profile.Option) profile.Profile) Option { return func(o *Options) { o.Profiles[name] = t diff --git a/util/file/client.go b/util/file/client.go index 3743ce3ff9..e94400c04e 100644 --- a/util/file/client.go +++ b/util/file/client.go @@ -12,7 +12,7 @@ import ( proto "go-micro.dev/v4/util/file/proto" ) -// Client is the client interface to access files +// Client is the client interface to access files. type File interface { Open(filename string, truncate bool) (int64, error) Stat(filename string) (*proto.StatResponse, error) @@ -26,7 +26,7 @@ type File interface { DownloadAt(filename, saveFile string, blockId int) error } -// NewClient returns a new Client which uses a micro Client +// NewClient returns a new Client which uses a micro Client. func New(service string, c client.Client) File { return &fc{proto.NewFileService(service, c)} } diff --git a/util/file/file.go b/util/file/file.go index 3e61d3f38b..27bf271500 100644 --- a/util/file/file.go +++ b/util/file/file.go @@ -2,7 +2,7 @@ package file import "os" -// Exists returns true if the path is existing +// Exists returns true if the path is existing. func Exists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { diff --git a/util/file/handler.go b/util/file/handler.go index 8f7288617c..cf638cb3aa 100644 --- a/util/file/handler.go +++ b/util/file/handler.go @@ -14,7 +14,7 @@ import ( proto "go-micro.dev/v4/util/file/proto" ) -// NewHandler is a handler that can be registered with a micro Server +// NewHandler is a handler that can be registered with a micro Server. func NewHandler(readDir string) proto.FileHandler { return &handler{ readDir: readDir, @@ -25,7 +25,7 @@ func NewHandler(readDir string) proto.FileHandler { } } -// RegisterHandler is a convenience method for registering a handler +// RegisterHandler is a convenience method for registering a handler. func RegisterHandler(s server.Server, readDir string) { proto.RegisterFileHandler(s, NewHandler(readDir)) } diff --git a/util/grpc/grpc.go b/util/grpc/grpc.go index 59c5a969df..c0b11005f1 100644 --- a/util/grpc/grpc.go +++ b/util/grpc/grpc.go @@ -9,7 +9,7 @@ import ( // Input: // Foo.Bar, /Foo/Bar, /package.Foo/Bar, /a.package.Foo/Bar // Output: -// [Foo, Bar] +// [Foo, Bar]. func ServiceMethod(m string) (string, string, error) { if len(m) == 0 { return "", "", fmt.Errorf("malformed method name: %q", m) @@ -40,7 +40,7 @@ func ServiceMethod(m string) (string, string, error) { } // ServiceFromMethod returns the service -// /service.Foo/Bar => service +// /service.Foo/Bar => service. func ServiceFromMethod(m string) string { if len(m) == 0 { return m diff --git a/util/http/http.go b/util/http/http.go index 5930f7938c..e4e857f22f 100644 --- a/util/http/http.go +++ b/util/http/http.go @@ -13,7 +13,7 @@ import ( "go-micro.dev/v4/selector" ) -// Write sets the status and body on a http ResponseWriter +// Write sets the status and body on a http ResponseWriter. func Write(w http.ResponseWriter, contentType string, status int, body string) { w.Header().Set("Content-Length", fmt.Sprintf("%v", len(body))) w.Header().Set("Content-Type", contentType) @@ -21,7 +21,7 @@ func Write(w http.ResponseWriter, contentType string, status int, body string) { fmt.Fprintf(w, `%v`, body) } -// WriteBadRequestError sets a 400 status code +// WriteBadRequestError sets a 400 status code. func WriteBadRequestError(w http.ResponseWriter, err error) { rawBody, err := json.Marshal(map[string]string{ "error": err.Error(), @@ -33,7 +33,7 @@ func WriteBadRequestError(w http.ResponseWriter, err error) { Write(w, "application/json", 400, string(rawBody)) } -// WriteInternalServerError sets a 500 status code +// WriteInternalServerError sets a 500 status code. func WriteInternalServerError(w http.ResponseWriter, err error) { rawBody, err := json.Marshal(map[string]string{ "error": err.Error(), diff --git a/util/http/http_test.go b/util/http/http_test.go index 7ec74bc639..78fba421b9 100644 --- a/util/http/http_test.go +++ b/util/http/http_test.go @@ -77,5 +77,4 @@ func TestRoundTripper(t *testing.T) { if string(b) != "hello world" { t.Fatal("response is", string(b)) } - } diff --git a/util/io/io.go b/util/io/io.go index 76465392e9..5ad3d3b86f 100644 --- a/util/io/io.go +++ b/util/io/io.go @@ -34,7 +34,7 @@ func (r *rwc) Close() error { return r.socket.Close() } -// NewRWC returns a new ReadWriteCloser +// NewRWC returns a new ReadWriteCloser. func NewRWC(sock transport.Socket) io.ReadWriteCloser { return &rwc{sock} } diff --git a/util/jitter/jitter.go b/util/jitter/jitter.go index 24e0700dfe..6198fc2257 100644 --- a/util/jitter/jitter.go +++ b/util/jitter/jitter.go @@ -10,7 +10,7 @@ var ( r = rand.New(rand.NewSource(time.Now().UnixNano())) ) -// Do returns a random time to jitter with max cap specified +// Do returns a random time to jitter with max cap specified. func Do(d time.Duration) time.Duration { v := r.Float64() * float64(d.Nanoseconds()) return time.Duration(v) diff --git a/util/kubernetes/api/api_test.go b/util/kubernetes/api/api_test.go index f1f45fdd80..294cafb26c 100644 --- a/util/kubernetes/api/api_test.go +++ b/util/kubernetes/api/api_test.go @@ -21,49 +21,49 @@ type testcase struct { type assertFn func(req *http.Request) bool var tests = []testcase{ - testcase{ + { ReqFn: func(opts *Options) *Request { return NewRequest(opts).Get().Resource("service") }, Method: "GET", URI: "/api/v1/namespaces/default/services/", }, - testcase{ + { ReqFn: func(opts *Options) *Request { return NewRequest(opts).Get().Resource("service").Name("foo") }, Method: "GET", URI: "/api/v1/namespaces/default/services/foo", }, - testcase{ + { ReqFn: func(opts *Options) *Request { return NewRequest(opts).Get().Resource("service").Namespace("test").Name("bar") }, Method: "GET", URI: "/api/v1/namespaces/test/services/bar", }, - testcase{ + { ReqFn: func(opts *Options) *Request { return NewRequest(opts).Get().Resource("deployment").Name("foo") }, Method: "GET", URI: "/apis/apps/v1/namespaces/default/deployments/foo", }, - testcase{ + { ReqFn: func(opts *Options) *Request { return NewRequest(opts).Get().Resource("deployment").Namespace("test").Name("foo") }, Method: "GET", URI: "/apis/apps/v1/namespaces/test/deployments/foo", }, - testcase{ + { ReqFn: func(opts *Options) *Request { return NewRequest(opts).Get().Resource("pod").Params(&Params{LabelSelector: map[string]string{"foo": "bar"}}) }, Method: "GET", URI: "/api/v1/namespaces/default/pods/?labelSelector=foo%3Dbar", }, - testcase{ + { ReqFn: func(opts *Options) *Request { return NewRequest(opts).Post().Resource("service").Name("foo").Body(map[string]string{"foo": "bar"}) }, @@ -71,7 +71,7 @@ var tests = []testcase{ URI: "/api/v1/namespaces/default/services/foo", Body: map[string]string{"foo": "bar"}, }, - testcase{ + { ReqFn: func(opts *Options) *Request { return NewRequest(opts).Post().Resource("deployment").Namespace("test").Name("foo").Body(map[string]string{"foo": "bar"}) }, @@ -79,7 +79,7 @@ var tests = []testcase{ URI: "/apis/apps/v1/namespaces/test/deployments/foo", Body: map[string]string{"foo": "bar"}, }, - testcase{ + { ReqFn: func(opts *Options) *Request { return NewRequest(opts).Put().Resource("endpoint").Name("baz").Body(map[string]string{"bam": "bar"}) }, @@ -87,7 +87,7 @@ var tests = []testcase{ URI: "/api/v1/namespaces/default/endpoints/baz", Body: map[string]string{"bam": "bar"}, }, - testcase{ + { ReqFn: func(opts *Options) *Request { return NewRequest(opts).Patch().Resource("endpoint").Name("baz").Body(map[string]string{"bam": "bar"}) }, @@ -95,7 +95,7 @@ var tests = []testcase{ URI: "/api/v1/namespaces/default/endpoints/baz", Body: map[string]string{"bam": "bar"}, }, - testcase{ + { ReqFn: func(opts *Options) *Request { return NewRequest(opts).Patch().Resource("endpoint").Name("baz").SetHeader("foo", "bar") }, @@ -103,7 +103,7 @@ var tests = []testcase{ URI: "/api/v1/namespaces/default/endpoints/baz", Header: map[string]string{"foo": "bar"}, }, - testcase{ + { ReqFn: func(opts *Options) *Request { return NewRequest(opts).Patch().Resource("deployment").Name("baz").SetHeader("foo", "bar") }, @@ -111,7 +111,7 @@ var tests = []testcase{ URI: "/apis/apps/v1/namespaces/default/deployments/baz", Header: map[string]string{"foo": "bar"}, }, - testcase{ + { ReqFn: func(opts *Options) *Request { return NewRequest(opts). Get(). diff --git a/util/kubernetes/api/request.go b/util/kubernetes/api/request.go index ea95422811..513a7cb1d7 100644 --- a/util/kubernetes/api/request.go +++ b/util/kubernetes/api/request.go @@ -40,7 +40,7 @@ type Params struct { Additional map[string]string } -// verb sets method +// verb sets method. func (r *Request) verb(method string) *Request { r.method = method return r @@ -50,32 +50,32 @@ func (r *Request) Context(ctx context.Context) { r.context = ctx } -// Get request +// Get request. func (r *Request) Get() *Request { return r.verb("GET") } -// Post request +// Post request. func (r *Request) Post() *Request { return r.verb("POST") } -// Put request +// Put request. func (r *Request) Put() *Request { return r.verb("PUT") } -// Patch request +// Patch request. func (r *Request) Patch() *Request { return r.verb("PATCH") } -// Delete request +// Delete request. func (r *Request) Delete() *Request { return r.verb("DELETE") } -// Namespace is to set the namespace to operate on +// Namespace is to set the namespace to operate on. func (r *Request) Namespace(s string) *Request { if len(s) > 0 { r.namespace = s @@ -84,26 +84,26 @@ func (r *Request) Namespace(s string) *Request { } // Resource is the type of resource the operation is -// for, such as "services", "endpoints" or "pods" +// for, such as "services", "endpoints" or "pods". func (r *Request) Resource(s string) *Request { r.resource = s return r } // SubResource sets a subresource on a resource, -// e.g. pods/log for pod logs +// e.g. pods/log for pod logs. func (r *Request) SubResource(s string) *Request { r.subResource = &s return r } -// Name is for targeting a specific resource by id +// Name is for targeting a specific resource by id. func (r *Request) Name(s string) *Request { r.resourceName = &s return r } -// Body pass in a body to set, this is for POST, PUT and PATCH requests +// Body pass in a body to set, this is for POST, PUT and PATCH requests. func (r *Request) Body(in interface{}) *Request { b := new(bytes.Buffer) // if we're not sending YAML request, we encode to JSON @@ -132,7 +132,6 @@ func (r *Request) Body(in interface{}) *Request { return r } -// Params isused to set paramters on a request func (r *Request) Params(p *Params) *Request { for k, v := range p.LabelSelector { // create new key=value pair @@ -152,13 +151,13 @@ func (r *Request) Params(p *Params) *Request { } // SetHeader sets a header on a request with -// a `key` and `value` +// a `key` and `value`. func (r *Request) SetHeader(key, value string) *Request { r.header.Add(key, value) return r } -// request builds the http.Request from the options +// request builds the http.Request from the options. func (r *Request) request() (*http.Request, error) { var url string switch r.resource { @@ -204,7 +203,7 @@ func (r *Request) request() (*http.Request, error) { return req, nil } -// Do builds and triggers the request +// Do builds and triggers the request. func (r *Request) Do() *Response { if r.err != nil { return &Response{ @@ -231,7 +230,7 @@ func (r *Request) Do() *Response { return newResponse(res, err) } -// Raw performs a Raw HTTP request to the Kubernetes API +// Raw performs a Raw HTTP request to the Kubernetes API. func (r *Request) Raw() (*http.Response, error) { req, err := r.request() if err != nil { @@ -253,7 +252,7 @@ type Options struct { Client *http.Client } -// NewRequest creates a k8s api request +// NewRequest creates a k8s api request. func NewRequest(opts *Options) *Request { req := &Request{ header: make(http.Header), diff --git a/util/kubernetes/api/response.go b/util/kubernetes/api/response.go index 94fe7fc7a9..1c574ae410 100644 --- a/util/kubernetes/api/response.go +++ b/util/kubernetes/api/response.go @@ -33,17 +33,17 @@ type Response struct { body []byte } -// Error returns an error +// Error returns an error. func (r *Response) Error() error { return r.err } -// StatusCode returns status code for response +// StatusCode returns status code for response. func (r *Response) StatusCode() int { return r.res.StatusCode } -// Into decode body into `data` +// Into decode body into `data`. func (r *Response) Into(data interface{}) error { if r.err != nil { return r.err diff --git a/util/kubernetes/client/client.go b/util/kubernetes/client/client.go index 83710a11cc..519f4a7bc2 100644 --- a/util/kubernetes/client/client.go +++ b/util/kubernetes/client/client.go @@ -17,13 +17,13 @@ import ( ) var ( - // path to kubernetes service account token + // path to kubernetes service account token. serviceAccountPath = "/var/run/secrets/kubernetes.io/serviceaccount" - // ErrReadNamespace is returned when the names could not be read from service account + // ErrReadNamespace is returned when the names could not be read from service account. ErrReadNamespace = errors.New("could not read namespace from service account secret") - // DefaultImage is default micro image + // DefaultImage is default micro image. DefaultImage = "micro/go-micro" - // DefaultNamespace is the default k8s namespace + // DefaultNamespace is the default k8s namespace. DefaultNamespace = "default" ) @@ -32,7 +32,7 @@ type client struct { opts *api.Options } -// Kubernetes client +// Kubernetes client. type Client interface { // Create creates new API resource Create(*Resource, ...CreateOption) error @@ -50,7 +50,7 @@ type Client interface { Watch(*Resource, ...WatchOption) (Watcher, error) } -// Create creates new API object +// Create creates new API object. func (c *client) Create(r *Resource, opts ...CreateOption) error { options := CreateOptions{ Namespace: c.opts.Namespace, @@ -79,12 +79,12 @@ var ( ) // SerializeResourceName removes all spacial chars from a string so it -// can be used as a k8s resource name +// can be used as a k8s resource name. func SerializeResourceName(ns string) string { return nameRegex.ReplaceAllString(ns, "-") } -// Get queries API objects and stores the result in r +// Get queries API objects and stores the result in r. func (c *client) Get(r *Resource, opts ...GetOption) error { options := GetOptions{ Namespace: c.opts.Namespace, @@ -102,7 +102,7 @@ func (c *client) Get(r *Resource, opts ...GetOption) error { Into(r.Value) } -// Log returns logs for a pod +// Log returns logs for a pod. func (c *client) Log(r *Resource, opts ...LogOption) (io.ReadCloser, error) { options := LogOptions{ Namespace: c.opts.Namespace, @@ -133,7 +133,7 @@ func (c *client) Log(r *Resource, opts ...LogOption) (io.ReadCloser, error) { return resp.Body, nil } -// Update updates API object +// Update updates API object. func (c *client) Update(r *Resource, opts ...UpdateOption) error { options := UpdateOptions{ Namespace: c.opts.Namespace, @@ -164,7 +164,7 @@ func (c *client) Update(r *Resource, opts ...UpdateOption) error { return resp.Error() } -// Delete removes API object +// Delete removes API object. func (c *client) Delete(r *Resource, opts ...DeleteOption) error { options := DeleteOptions{ Namespace: c.opts.Namespace, @@ -182,7 +182,7 @@ func (c *client) Delete(r *Resource, opts ...DeleteOption) error { return resp.Error() } -// List lists API objects and stores the result in r +// List lists API objects and stores the result in r. func (c *client) List(r *Resource, opts ...ListOption) error { options := ListOptions{ Namespace: c.opts.Namespace, @@ -194,7 +194,7 @@ func (c *client) List(r *Resource, opts ...ListOption) error { return c.Get(r, GetNamespace(options.Namespace)) } -// Watch returns an event stream +// Watch returns an event stream. func (c *client) Watch(r *Resource, opts ...WatchOption) (Watcher, error) { options := WatchOptions{ Namespace: c.opts.Namespace, @@ -225,7 +225,7 @@ func (c *client) Watch(r *Resource, opts ...WatchOption) (Watcher, error) { return newWatcher(req) } -// NewService returns default micro kubernetes service definition +// NewService returns default micro kubernetes service definition. func NewService(name, version, typ, namespace string) *Service { if logger.V(logger.TraceLevel, logger.DefaultLogger) { logger.Logf(logger.TraceLevel, "kubernetes default service: name: %s, version: %s", name, version) @@ -268,7 +268,7 @@ func NewService(name, version, typ, namespace string) *Service { } } -// NewService returns default micro kubernetes deployment definition +// NewService returns default micro kubernetes deployment definition. func NewDeployment(name, version, typ, namespace string) *Deployment { if logger.V(logger.TraceLevel, logger.DefaultLogger) { logger.Logf(logger.TraceLevel, "kubernetes default deployment: name: %s, version: %s", name, version) @@ -333,7 +333,7 @@ func NewDeployment(name, version, typ, namespace string) *Deployment { } } -// NewLocalClient returns a client that can be used with `kubectl proxy` +// NewLocalClient returns a client that can be used with `kubectl proxy`. func NewLocalClient(hosts ...string) *client { if len(hosts) == 0 { hosts[0] = "http://localhost:8001" diff --git a/util/kubernetes/client/options.go b/util/kubernetes/client/options.go index dd6b32a572..96fa6697ad 100644 --- a/util/kubernetes/client/options.go +++ b/util/kubernetes/client/options.go @@ -36,70 +36,70 @@ type ListOption func(*ListOptions) type LogOption func(*LogOptions) type WatchOption func(*WatchOptions) -// LogParams provides additional params for logs +// LogParams provides additional params for logs. func LogParams(p map[string]string) LogOption { return func(l *LogOptions) { l.Params = p } } -// WatchParams used for watch params +// WatchParams used for watch params. func WatchParams(p map[string]string) WatchOption { return func(w *WatchOptions) { w.Params = p } } -// CreateNamespace sets the namespace for creating a resource +// CreateNamespace sets the namespace for creating a resource. func CreateNamespace(ns string) CreateOption { return func(o *CreateOptions) { o.Namespace = SerializeResourceName(ns) } } -// GetNamespace sets the namespace for getting a resource +// GetNamespace sets the namespace for getting a resource. func GetNamespace(ns string) GetOption { return func(o *GetOptions) { o.Namespace = SerializeResourceName(ns) } } -// GetLabels sets the labels for when getting a resource +// GetLabels sets the labels for when getting a resource. func GetLabels(ls map[string]string) GetOption { return func(o *GetOptions) { o.Labels = ls } } -// UpdateNamespace sets the namespace for updating a resource +// UpdateNamespace sets the namespace for updating a resource. func UpdateNamespace(ns string) UpdateOption { return func(o *UpdateOptions) { o.Namespace = SerializeResourceName(ns) } } -// DeleteNamespace sets the namespace for deleting a resource +// DeleteNamespace sets the namespace for deleting a resource. func DeleteNamespace(ns string) DeleteOption { return func(o *DeleteOptions) { o.Namespace = SerializeResourceName(ns) } } -// ListNamespace sets the namespace for listing resources +// ListNamespace sets the namespace for listing resources. func ListNamespace(ns string) ListOption { return func(o *ListOptions) { o.Namespace = SerializeResourceName(ns) } } -// LogNamespace sets the namespace for logging a resource +// LogNamespace sets the namespace for logging a resource. func LogNamespace(ns string) LogOption { return func(o *LogOptions) { o.Namespace = SerializeResourceName(ns) } } -// WatchNamespace sets the namespace for watching a resource +// WatchNamespace sets the namespace for watching a resource. func WatchNamespace(ns string) WatchOption { return func(o *WatchOptions) { o.Namespace = SerializeResourceName(ns) diff --git a/util/kubernetes/client/templates.go b/util/kubernetes/client/templates.go index ce0e3b0e7a..92f80d0130 100644 --- a/util/kubernetes/client/templates.go +++ b/util/kubernetes/client/templates.go @@ -9,7 +9,7 @@ var templates = map[string]string{ } // stripped image pull policy always -// imagePullPolicy: Always +// imagePullPolicy: Always. var deploymentTmpl = ` apiVersion: apps/v1 kind: Deployment diff --git a/util/kubernetes/client/types.go b/util/kubernetes/client/types.go index 1dc13e4e57..8a68a89166 100644 --- a/util/kubernetes/client/types.go +++ b/util/kubernetes/client/types.go @@ -1,6 +1,6 @@ package client -// ContainerPort +// ContainerPort. type ContainerPort struct { Name string `json:"name,omitempty"` HostPort int `json:"hostPort,omitempty"` @@ -8,7 +8,7 @@ type ContainerPort struct { Protocol string `json:"protocol,omitempty"` } -// EnvVar is environment variable +// EnvVar is environment variable. type EnvVar struct { Name string `json:"name"` Value string `json:"value,omitempty"` @@ -20,7 +20,7 @@ type Condition struct { Message string `json:"message,omitempty"` } -// Container defined container runtime values +// Container defined container runtime values. type Container struct { Name string `json:"name"` Image string `json:"image"` @@ -30,14 +30,14 @@ type Container struct { Ports []ContainerPort `json:"ports,omitempty"` } -// DeploymentSpec defines micro deployment spec +// DeploymentSpec defines micro deployment spec. type DeploymentSpec struct { Replicas int `json:"replicas,omitempty"` Selector *LabelSelector `json:"selector"` Template *Template `json:"template,omitempty"` } -// DeploymentCondition describes the state of deployment +// DeploymentCondition describes the state of deployment. type DeploymentCondition struct { LastUpdateTime string `json:"lastUpdateTime"` Type string `json:"type"` @@ -45,7 +45,7 @@ type DeploymentCondition struct { Message string `json:"message,omitempty"` } -// DeploymentStatus is returned when querying deployment +// DeploymentStatus is returned when querying deployment. type DeploymentStatus struct { Replicas int `json:"replicas,omitempty"` UpdatedReplicas int `json:"updatedReplicas,omitempty"` @@ -55,20 +55,20 @@ type DeploymentStatus struct { Conditions []DeploymentCondition `json:"conditions,omitempty"` } -// Deployment is Kubernetes deployment +// Deployment is Kubernetes deployment. type Deployment struct { Metadata *Metadata `json:"metadata"` Spec *DeploymentSpec `json:"spec,omitempty"` Status *DeploymentStatus `json:"status,omitempty"` } -// DeploymentList +// DeploymentList. type DeploymentList struct { Items []Deployment `json:"items"` } // LabelSelector is a label query over a set of resources -// NOTE: we do not support MatchExpressions at the moment +// NOTE: we do not support MatchExpressions at the moment. type LabelSelector struct { MatchLabels map[string]string `json:"matchLabels,omitempty"` } @@ -82,7 +82,7 @@ type LoadBalancerStatus struct { Ingress []LoadBalancerIngress `json:"ingress,omitempty"` } -// Metadata defines api object metadata +// Metadata defines api object metadata. type Metadata struct { Name string `json:"name,omitempty"` Namespace string `json:"namespace,omitempty"` @@ -91,25 +91,25 @@ type Metadata struct { Annotations map[string]string `json:"annotations,omitempty"` } -// PodSpec is a pod +// PodSpec is a pod. type PodSpec struct { Containers []Container `json:"containers"` ServiceAccountName string `json:"serviceAccountName"` } -// PodList +// PodList. type PodList struct { Items []Pod `json:"items"` } -// Pod is the top level item for a pod +// Pod is the top level item for a pod. type Pod struct { Metadata *Metadata `json:"metadata"` Spec *PodSpec `json:"spec,omitempty"` Status *PodStatus `json:"status"` } -// PodStatus +// PodStatus. type PodStatus struct { Conditions []PodCondition `json:"conditions,omitempty"` Containers []ContainerStatus `json:"containerStatuses"` @@ -118,7 +118,7 @@ type PodStatus struct { Reason string `json:"reason"` } -// PodCondition describes the state of pod +// PodCondition describes the state of pod. type PodCondition struct { Type string `json:"type"` Reason string `json:"reason,omitempty"` @@ -135,21 +135,21 @@ type ContainerState struct { Waiting *Condition `json:"waiting"` } -// Resource is API resource +// Resource is API resource. type Resource struct { Name string Kind string Value interface{} } -// ServicePort configures service ports +// ServicePort configures service ports. type ServicePort struct { Name string `json:"name,omitempty"` Port int `json:"port"` Protocol string `json:"protocol,omitempty"` } -// ServiceSpec provides service configuration +// ServiceSpec provides service configuration. type ServiceSpec struct { ClusterIP string `json:"clusterIP"` Type string `json:"type,omitempty"` @@ -157,52 +157,52 @@ type ServiceSpec struct { Ports []ServicePort `json:"ports,omitempty"` } -// ServiceStatus +// ServiceStatus. type ServiceStatus struct { LoadBalancer LoadBalancerStatus `json:"loadBalancer,omitempty"` } -// Service is kubernetes service +// Service is kubernetes service. type Service struct { Metadata *Metadata `json:"metadata"` Spec *ServiceSpec `json:"spec,omitempty"` Status *ServiceStatus `json:"status,omitempty"` } -// ServiceList +// ServiceList. type ServiceList struct { Items []Service `json:"items"` } -// Template is micro deployment template +// Template is micro deployment template. type Template struct { Metadata *Metadata `json:"metadata,omitempty"` PodSpec *PodSpec `json:"spec,omitempty"` } -// Namespace is a Kubernetes Namespace +// Namespace is a Kubernetes Namespace. type Namespace struct { Metadata *Metadata `json:"metadata,omitempty"` } -// NamespaceList +// NamespaceList. type NamespaceList struct { Items []Namespace `json:"items"` } -// ImagePullSecret +// ImagePullSecret. type ImagePullSecret struct { Name string `json:"name"` } -// Secret +// Secret. type Secret struct { Type string `json:"type,omitempty"` Data map[string]string `json:"data"` Metadata *Metadata `json:"metadata"` } -// ServiceAccount +// ServiceAccount. type ServiceAccount struct { Metadata *Metadata `json:"metadata,omitempty"` ImagePullSecrets []ImagePullSecret `json:"imagePullSecrets,omitempty"` diff --git a/util/kubernetes/client/util.go b/util/kubernetes/client/util.go index 72c6e53d6f..ebce6d794b 100644 --- a/util/kubernetes/client/util.go +++ b/util/kubernetes/client/util.go @@ -11,7 +11,7 @@ import ( "text/template" ) -// renderTemplateFile renders template for a given resource into writer w +// renderTemplateFile renders template for a given resource into writer w. func renderTemplate(resource string, w io.Writer, data interface{}) error { t := template.Must(template.New("kubernetes").Parse(templates[resource])) @@ -26,7 +26,7 @@ func renderTemplate(resource string, w io.Writer, data interface{}) error { // https://github.com/kubernetes/kubernetes/blob/7a725418af4661067b56506faabc2d44c6d7703a/pkg/util/crypto/crypto.go // CertPoolFromFile returns an x509.CertPool containing the certificates in the given PEM-encoded file. -// Returns an error if the file could not be read, a certificate could not be parsed, or if the file does not contain any certificates +// Returns an error if the file could not be read, a certificate could not be parsed, or if the file does not contain any certificates. func CertPoolFromFile(filename string) (*x509.CertPool, error) { certs, err := certificatesFromFile(filename) if err != nil { @@ -40,7 +40,7 @@ func CertPoolFromFile(filename string) (*x509.CertPool, error) { } // certificatesFromFile returns the x509.Certificates contained in the given PEM-encoded file. -// Returns an error if the file could not be read, a certificate could not be parsed, or if the file does not contain any certificates +// Returns an error if the file could not be read, a certificate could not be parsed, or if the file does not contain any certificates. func certificatesFromFile(file string) ([]*x509.Certificate, error) { if len(file) == 0 { return nil, errors.New("error reading certificates from an empty filename") @@ -57,7 +57,7 @@ func certificatesFromFile(file string) ([]*x509.Certificate, error) { } // CertsFromPEM returns the x509.Certificates contained in the given PEM-encoded byte array -// Returns an error if a certificate could not be parsed, or if the data does not contain any certificates +// Returns an error if a certificate could not be parsed, or if the data does not contain any certificates. func CertsFromPEM(pemCerts []byte) ([]*x509.Certificate, error) { ok := false certs := []*x509.Certificate{} @@ -87,7 +87,7 @@ func CertsFromPEM(pemCerts []byte) ([]*x509.Certificate, error) { return certs, nil } -// Format is used to format a string value into a k8s valid name +// Format is used to format a string value into a k8s valid name. func Format(v string) string { // to lower case v = strings.ToLower(v) diff --git a/util/kubernetes/client/watch.go b/util/kubernetes/client/watch.go index e4e757f7ae..f3ab63a655 100644 --- a/util/kubernetes/client/watch.go +++ b/util/kubernetes/client/watch.go @@ -11,14 +11,14 @@ import ( ) const ( - // EventTypes used + // EventTypes used. Added EventType = "ADDED" Modified EventType = "MODIFIED" Deleted EventType = "DELETED" Error EventType = "ERROR" ) -// Watcher is used to watch for events +// Watcher is used to watch for events. type Watcher interface { // A channel of events Chan() <-chan Event @@ -35,7 +35,7 @@ type Event struct { Object json.RawMessage `json:"object"` } -// bodyWatcher scans the body of a request for chunks +// bodyWatcher scans the body of a request for chunks. type bodyWatcher struct { results chan Event cancel func() @@ -44,12 +44,12 @@ type bodyWatcher struct { req *api.Request } -// Changes returns the results channel +// Changes returns the results channel. func (wr *bodyWatcher) Chan() <-chan Event { return wr.results } -// Stop cancels the request +// Stop cancels the request. func (wr *bodyWatcher) Stop() { select { case <-wr.stop: @@ -89,7 +89,7 @@ func (wr *bodyWatcher) stream() { } // newWatcher creates a k8s body watcher for -// a given http request +// a given http request. func newWatcher(req *api.Request) (Watcher, error) { // set request context so we can cancel the request ctx, cancel := context.WithCancel(context.Background()) diff --git a/util/log/README.md b/util/log/README.md deleted file mode 100644 index 99b6bc5ea1..0000000000 --- a/util/log/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# Log - -DEPRECATED: use go-micro.dev/v4/logger interface - -This is the global logger for all micro based libraries. - -## Set Logger - -Set the logger for micro libraries - -```go -// import go-micro/util/log -import "github.com/micro/go-micro/util/log" - -// SetLogger expects github.com/micro/go-micro/debug/log.Log interface -log.SetLogger(mylogger) -``` diff --git a/util/log/log.go b/util/log/log.go deleted file mode 100644 index 2f96acb53c..0000000000 --- a/util/log/log.go +++ /dev/null @@ -1,227 +0,0 @@ -// Package log is a global internal logger -// DEPRECATED: this is frozen package, use go-micro.dev/v4/logger -package log - -import ( - "fmt" - "os" - "sync/atomic" - - dlog "go-micro.dev/v4/debug/log" - nlog "go-micro.dev/v4/logger" -) - -// level is a log level -type Level int32 - -const ( - LevelFatal Level = iota - LevelError - LevelWarn - LevelInfo - LevelDebug - LevelTrace -) - -type elog struct { - dlog dlog.Log -} - -var ( - // the local logger - logger dlog.Log = &elog{} - - // default log level is info - level = LevelInfo - - // prefix for all messages - prefix string -) - -func levelToLevel(l Level) nlog.Level { - switch l { - case LevelTrace: - return nlog.TraceLevel - case LevelDebug: - return nlog.DebugLevel - case LevelWarn: - return nlog.WarnLevel - case LevelInfo: - return nlog.InfoLevel - case LevelError: - return nlog.ErrorLevel - case LevelFatal: - return nlog.FatalLevel - } - return nlog.InfoLevel -} - -func init() { - switch os.Getenv("MICRO_LOG_LEVEL") { - case "trace": - level = LevelTrace - case "debug": - level = LevelDebug - case "warn": - level = LevelWarn - case "info": - level = LevelInfo - case "error": - level = LevelError - case "fatal": - level = LevelFatal - } -} - -func (l Level) String() string { - switch l { - case LevelTrace: - return "trace" - case LevelDebug: - return "debug" - case LevelWarn: - return "warn" - case LevelInfo: - return "info" - case LevelError: - return "error" - case LevelFatal: - return "fatal" - default: - return "unknown" - } -} - -func (el *elog) Read(opt ...dlog.ReadOption) ([]dlog.Record, error) { - return el.dlog.Read(opt...) -} - -func (el *elog) Write(r dlog.Record) error { - return el.dlog.Write(r) -} - -func (el *elog) Stream() (dlog.Stream, error) { - return el.dlog.Stream() -} - -// Log makes use of github.com/micro/debug/log -func Log(v ...interface{}) { - if len(prefix) > 0 { - v = append([]interface{}{prefix, " "}, v...) - } - nlog.DefaultLogger.Log(levelToLevel(level), v) -} - -// Logf makes use of github.com/micro/debug/log -func Logf(format string, v ...interface{}) { - if len(prefix) > 0 { - format = prefix + " " + format - } - nlog.DefaultLogger.Logf(levelToLevel(level), format, v) -} - -// WithLevel logs with the level specified -func WithLevel(l Level, v ...interface{}) { - if l > level { - return - } - Log(v...) -} - -// WithLevel logs with the level specified -func WithLevelf(l Level, format string, v ...interface{}) { - if l > level { - return - } - Logf(format, v...) -} - -// Trace provides trace level logging -func Trace(v ...interface{}) { - WithLevel(LevelTrace, v...) -} - -// Tracef provides trace level logging -func Tracef(format string, v ...interface{}) { - WithLevelf(LevelTrace, format, v...) -} - -// Debug provides debug level logging -func Debug(v ...interface{}) { - WithLevel(LevelDebug, v...) -} - -// Debugf provides debug level logging -func Debugf(format string, v ...interface{}) { - WithLevelf(LevelDebug, format, v...) -} - -// Warn provides warn level logging -func Warn(v ...interface{}) { - WithLevel(LevelWarn, v...) -} - -// Warnf provides warn level logging -func Warnf(format string, v ...interface{}) { - WithLevelf(LevelWarn, format, v...) -} - -// Info provides info level logging -func Info(v ...interface{}) { - WithLevel(LevelInfo, v...) -} - -// Infof provides info level logging -func Infof(format string, v ...interface{}) { - WithLevelf(LevelInfo, format, v...) -} - -// Error provides warn level logging -func Error(v ...interface{}) { - WithLevel(LevelError, v...) -} - -// Errorf provides warn level logging -func Errorf(format string, v ...interface{}) { - WithLevelf(LevelError, format, v...) -} - -// Fatal logs with Log and then exits with os.Exit(1) -func Fatal(v ...interface{}) { - WithLevel(LevelFatal, v...) -} - -// Fatalf logs with Logf and then exits with os.Exit(1) -func Fatalf(format string, v ...interface{}) { - WithLevelf(LevelFatal, format, v...) -} - -// SetLogger sets the local logger -func SetLogger(l dlog.Log) { - logger = l -} - -// GetLogger returns the local logger -func GetLogger() dlog.Log { - return logger -} - -// SetLevel sets the log level -func SetLevel(l Level) { - atomic.StoreInt32((*int32)(&level), int32(l)) -} - -// GetLevel returns the current level -func GetLevel() Level { - return level -} - -// Set a prefix for the logger -func SetPrefix(p string) { - prefix = p -} - -// Set service name -func Name(name string) { - prefix = fmt.Sprintf("[%s]", name) -} diff --git a/util/mdns/client.go b/util/mdns/client.go index c6e2139024..4f9197bc10 100644 --- a/util/mdns/client.go +++ b/util/mdns/client.go @@ -15,7 +15,7 @@ import ( "go-micro.dev/v4/logger" ) -// ServiceEntry is returned after we query for a service +// ServiceEntry is returned after we query for a service. type ServiceEntry struct { Name string Host string @@ -33,13 +33,12 @@ type ServiceEntry struct { sent bool } -// complete is used to check if we have all the info we need +// complete is used to check if we have all the info we need. func (s *ServiceEntry) complete() bool { - return (len(s.AddrV4) > 0 || len(s.AddrV6) > 0 || len(s.Addr) > 0) && s.Port != 0 && s.hasTXT } -// QueryParam is used to customize how a Lookup is performed +// QueryParam is used to customize how a Lookup is performed. type QueryParam struct { Service string // Service to lookup Domain string // Lookup domain, default "local" @@ -51,7 +50,7 @@ type QueryParam struct { WantUnicastResponse bool // Unicast response desired, as per 5.4 in RFC } -// DefaultParams is used to return a default set of QueryParam's +// DefaultParams is used to return a default set of QueryParam's. func DefaultParams(service string) *QueryParam { return &QueryParam{ Service: service, @@ -100,7 +99,7 @@ func Query(params *QueryParam) error { return client.query(params) } -// Listen listens indefinitely for multicast updates +// Listen listens indefinitely for multicast updates. func Listen(entries chan<- *ServiceEntry, exit chan struct{}) error { // Create a new client client, err := newClient() @@ -156,7 +155,7 @@ func Listen(entries chan<- *ServiceEntry, exit chan struct{}) error { return nil } -// Lookup is the same as Query, however it uses all the default parameters +// Lookup is the same as Query, however it uses all the default parameters. func Lookup(service string, entries chan<- *ServiceEntry) error { params := DefaultParams(service) params.Entries = entries @@ -164,7 +163,7 @@ func Lookup(service string, entries chan<- *ServiceEntry) error { } // Client provides a query interface that can be used to -// search for service providers using mDNS +// search for service providers using mDNS. type client struct { ipv4UnicastConn *net.UDPConn ipv6UnicastConn *net.UDPConn @@ -178,7 +177,7 @@ type client struct { } // NewClient creates a new mdns Client that can be used to query -// for records +// for records. func newClient() (*client, error) { // TODO(reddaly): At least attempt to bind to the port required in the spec. // Create a IPv4 listener @@ -253,7 +252,7 @@ func newClient() (*client, error) { return c, nil } -// Close is used to cleanup the client +// Close is used to cleanup the client. func (c *client) Close() error { c.closeLock.Lock() defer c.closeLock.Unlock() @@ -281,8 +280,8 @@ func (c *client) Close() error { return nil } -// setInterface is used to set the query interface, uses sytem -// default if not provided +// setInterface is used to set the query interface, uses system +// default if not provided. func (c *client) setInterface(iface *net.Interface, loopback bool) error { p := ipv4.NewPacketConn(c.ipv4UnicastConn) if err := p.JoinGroup(iface, &net.UDPAddr{IP: mdnsGroupIPv4}); err != nil { @@ -309,7 +308,7 @@ func (c *client) setInterface(iface *net.Interface, loopback bool) error { return nil } -// query is used to perform a lookup and stream results +// query is used to perform a lookup and stream results. func (c *client) query(params *QueryParam) error { // Create the service name serviceAddr := fmt.Sprintf("%s.%s.", trimDot(params.Service), trimDot(params.Domain)) @@ -385,7 +384,7 @@ func (c *client) query(params *QueryParam) error { } } -// sendQuery is used to multicast a query out +// sendQuery is used to multicast a query out. func (c *client) sendQuery(q *dns.Msg) error { buf, err := q.Pack() if err != nil { @@ -400,7 +399,7 @@ func (c *client) sendQuery(q *dns.Msg) error { return nil } -// recv is used to receive until we get a shutdown +// recv is used to receive until we get a shutdown. func (c *client) recv(l *net.UDPConn, msgCh chan *dns.Msg) { if l == nil { return @@ -429,7 +428,7 @@ func (c *client) recv(l *net.UDPConn, msgCh chan *dns.Msg) { } } -// ensureName is used to ensure the named node is in progress +// ensureName is used to ensure the named node is in progress. func ensureName(inprogress map[string]*ServiceEntry, name string, typ uint16) *ServiceEntry { if inp, ok := inprogress[name]; ok { return inp @@ -442,7 +441,7 @@ func ensureName(inprogress map[string]*ServiceEntry, name string, typ uint16) *S return inp } -// alias is used to setup an alias between two entries +// alias is used to setup an alias between two entries. func alias(inprogress map[string]*ServiceEntry, src, dst string, typ uint16) { srcEntry := ensureName(inprogress, src, typ) inprogress[dst] = srcEntry diff --git a/util/mdns/dns_sd.go b/util/mdns/dns_sd.go index 0fd84a8e26..9ff4879bdf 100644 --- a/util/mdns/dns_sd.go +++ b/util/mdns/dns_sd.go @@ -46,7 +46,7 @@ func (s *DNSSDService) Records(q dns.Question) []dns.RR { // issued to browse for DNS-SD services, as per section 9. of RFC6763. // // A meta-query has a name of the form "_services._dns-sd._udp." where -// Domain is a fully-qualified domain, such as "local." +// Domain is a fully-qualified domain, such as "local.". func (s *DNSSDService) dnssdMetaQueryRecords(q dns.Question) []dns.RR { // Intended behavior, as described in the RFC: // ...it may be useful for network administrators to find the list of @@ -80,6 +80,6 @@ func (s *DNSSDService) dnssdMetaQueryRecords(q dns.Question) []dns.RR { // Announcement returns DNS records that should be broadcast during the initial // availability of the service, as described in section 8.3 of RFC 6762. // TODO(reddaly): Add this when Announcement is added to the mdns.Zone interface. -//func (s *DNSSDService) Announcement() []dns.RR { +// func (s *DNSSDService) Announcement() []dns.RR { // return s.MDNSService.Announcement() //} diff --git a/util/mdns/dns_sd_test.go b/util/mdns/dns_sd_test.go index d973fd7e63..8b4c11ce5f 100644 --- a/util/mdns/dns_sd_test.go +++ b/util/mdns/dns_sd_test.go @@ -3,8 +3,9 @@ package mdns import ( "reflect" "testing" + + "github.com/miekg/dns" ) -import "github.com/miekg/dns" type mockMDNSService struct{} diff --git a/util/mdns/server.go b/util/mdns/server.go index b100574af9..2e68fcdb28 100644 --- a/util/mdns/server.go +++ b/util/mdns/server.go @@ -18,7 +18,7 @@ var ( mdnsGroupIPv4 = net.ParseIP("224.0.0.251") mdnsGroupIPv6 = net.ParseIP("ff02::fb") - // mDNS wildcard addresses + // mDNS wildcard addresses. mdnsWildcardAddrIPv4 = &net.UDPAddr{ IP: net.ParseIP("224.0.0.0"), Port: 5353, @@ -28,7 +28,7 @@ var ( Port: 5353, } - // mDNS endpoint addresses + // mDNS endpoint addresses. ipv4Addr = &net.UDPAddr{ IP: mdnsGroupIPv4, Port: 5353, @@ -40,10 +40,10 @@ var ( ) // GetMachineIP is a func which returns the outbound IP of this machine. -// Used by the server to determine whether to attempt send the response on a local address +// Used by the server to determine whether to attempt send the response on a local address. type GetMachineIP func() net.IP -// Config is used to configure the mDNS server +// Config is used to configure the mDNS server. type Config struct { // Zone must be provided to support responding to queries Zone Zone @@ -64,7 +64,7 @@ type Config struct { } // Server is an mDNS server used to listen for mDNS queries and respond if we -// have a matching local record +// have a matching local record. type Server struct { config *Config @@ -79,7 +79,7 @@ type Server struct { outboundIP net.IP } -// NewServer is used to create a new mDNS server from a config +// NewServer is used to create a new mDNS server from a config. func NewServer(config *Config) (*Server, error) { setCustomPort(config.Port) @@ -152,7 +152,7 @@ func NewServer(config *Config) (*Server, error) { return s, nil } -// Shutdown is used to shutdown the listener +// Shutdown is used to shutdown the listener. func (s *Server) Shutdown() error { s.shutdownLock.Lock() defer s.shutdownLock.Unlock() @@ -176,7 +176,7 @@ func (s *Server) Shutdown() error { return nil } -// recv is a long running routine to receive packets from an interface +// recv is a long running routine to receive packets from an interface. func (s *Server) recv(c *net.UDPConn) { if c == nil { return @@ -199,7 +199,7 @@ func (s *Server) recv(c *net.UDPConn) { } } -// parsePacket is used to parse an incoming packet +// parsePacket is used to parse an incoming packet. func (s *Server) parsePacket(packet []byte, from net.Addr) error { var msg dns.Msg if err := msg.Unpack(packet); err != nil { @@ -213,7 +213,7 @@ func (s *Server) parsePacket(packet []byte, from net.Addr) error { return s.handleQuery(&msg, from) } -// handleQuery is used to handle an incoming query +// handleQuery is used to handle an incoming query. func (s *Server) handleQuery(query *dns.Msg, from net.Addr) error { if query.Opcode != dns.OpcodeQuery { // "In both multicast query and multicast response messages, the OPCODE MUST @@ -421,7 +421,7 @@ func (s *Server) probe() { } } -// SendMulticast us used to send a multicast response packet +// SendMulticast us used to send a multicast response packet. func (s *Server) SendMulticast(msg *dns.Msg) error { buf, err := msg.Pack() if err != nil { @@ -436,7 +436,7 @@ func (s *Server) SendMulticast(msg *dns.Msg) error { return nil } -// sendResponse is used to send a response packet +// sendResponse is used to send a response packet. func (s *Server) sendResponse(resp *dns.Msg, from net.Addr) error { // TODO(reddaly): Respect the unicast argument, and allow sending responses // over multicast. @@ -463,7 +463,6 @@ func (s *Server) sendResponse(resp *dns.Msg, from net.Addr) error { conn.WriteToUDP(buf, &net.UDPAddr{IP: backupTarget, Port: addr.Port}) } return err - } func (s *Server) unregister() error { @@ -502,7 +501,6 @@ func setCustomPort(port int) { } } -// getOutboundIP returns the IP address of this machine as seen when dialling out func getOutboundIP() net.IP { conn, err := net.Dial("udp", "8.8.8.8:80") if err != nil { diff --git a/util/mdns/zone.go b/util/mdns/zone.go index abbab4bd23..d5bfbe1498 100644 --- a/util/mdns/zone.go +++ b/util/mdns/zone.go @@ -16,13 +16,13 @@ const ( ) // Zone is the interface used to integrate with the server and -// to serve records dynamically +// to serve records dynamically. type Zone interface { // Records returns DNS records in response to a DNS question. Records(q dns.Question) []dns.RR } -// MDNSService is used to export a named service by implementing a Zone +// MDNSService is used to export a named service by implementing a Zone. type MDNSService struct { Instance string // Instance name (e.g. "hostService name") Service string // Service name (e.g. "_http._tcp.") @@ -130,7 +130,7 @@ func NewMDNSService(instance, service, domain, hostName string, port int, ips [] }, nil } -// trimDot is used to trim the dots from the start or end of a string +// trimDot is used to trim the dots from the start or end of a string. func trimDot(s string) string { return strings.Trim(s, ".") } @@ -174,7 +174,7 @@ func (m *MDNSService) serviceEnum(q dns.Question) []dns.RR { } } -// serviceRecords is called when the query matches the service name +// serviceRecords is called when the query matches the service name. func (m *MDNSService) serviceRecords(q dns.Question) []dns.RR { switch q.Qtype { case dns.TypeANY: @@ -205,7 +205,7 @@ func (m *MDNSService) serviceRecords(q dns.Question) []dns.RR { } } -// serviceRecords is called when the query matches the instance name +// serviceRecords is called when the query matches the instance name. func (m *MDNSService) instanceRecords(q dns.Question) []dns.RR { switch q.Qtype { case dns.TypeANY: diff --git a/util/net/net.go b/util/net/net.go index 02d6ad2f82..6ee0e8c047 100644 --- a/util/net/net.go +++ b/util/net/net.go @@ -9,7 +9,7 @@ import ( "strings" ) -// HostPort format addr and port suitable for dial +// HostPort format addr and port suitable for dial. func HostPort(addr string, port interface{}) string { host := addr if strings.Count(addr, ":") > 0 { @@ -26,9 +26,8 @@ func HostPort(addr string, port interface{}) string { } // Listen takes addr:portmin-portmax and binds to the first available port -// Example: Listen("localhost:5000-6000", fn) +// Example: Listen("localhost:5000-6000", fn). func Listen(addr string, fn func(string) (net.Listener, error)) (net.Listener, error) { - if strings.Count(addr, ":") == 1 && strings.Count(addr, "-") == 0 { return fn(addr) } @@ -79,7 +78,7 @@ func Listen(addr string, fn func(string) (net.Listener, error)) (net.Listener, e return nil, fmt.Errorf("unable to bind to %s", addr) } -// Proxy returns the proxy and the address if it exits +// Proxy returns the proxy and the address if it exits. func Proxy(service string, address []string) (string, []string, bool) { var hasProxy bool diff --git a/util/net/net_test.go b/util/net/net_test.go index 28d490d47b..98b9039a8d 100644 --- a/util/net/net_test.go +++ b/util/net/net_test.go @@ -23,10 +23,9 @@ func TestListen(t *testing.T) { // TODO nats case test // natsAddr := "_INBOX.bID2CMRvlNp0vt4tgNBHWf" // Expect addr DO NOT has extra ":" at the end! - } -// TestProxyEnv checks whether we have proxy/network settings in env +// TestProxyEnv checks whether we have proxy/network settings in env. func TestProxyEnv(t *testing.T) { service := "foo" address := []string{"bar"} diff --git a/util/pki/certoptions.go b/util/pki/certoptions.go index 61026967de..2a9e0cf138 100644 --- a/util/pki/certoptions.go +++ b/util/pki/certoptions.go @@ -9,7 +9,7 @@ import ( "time" ) -// CertOptions are passed to cert options +// CertOptions are passed to cert options. type CertOptions struct { IsCA bool Subject pkix.Name @@ -24,38 +24,38 @@ type CertOptions struct { Priv ed25519.PrivateKey } -// CertOption sets CertOptions +// CertOption sets CertOptions. type CertOption func(c *CertOptions) -// Subject sets the Subject field +// Subject sets the Subject field. func Subject(subject pkix.Name) CertOption { return func(c *CertOptions) { c.Subject = subject } } -// IsCA states the cert is a CA +// IsCA states the cert is a CA. func IsCA() CertOption { return func(c *CertOptions) { c.IsCA = true } } -// DNSNames is a list of hosts to sign in to the certificate +// DNSNames is a list of hosts to sign in to the certificate. func DNSNames(names ...string) CertOption { return func(c *CertOptions) { c.DNSNames = names } } -// IPAddresses is a list of IPs to sign in to the certificate +// IPAddresses is a list of IPs to sign in to the certificate. func IPAddresses(ips ...net.IP) CertOption { return func(c *CertOptions) { c.IPAddresses = ips } } -// KeyPair is the key pair to sign the certificate with +// KeyPair is the key pair to sign the certificate with. func KeyPair(pub ed25519.PublicKey, priv ed25519.PrivateKey) CertOption { return func(c *CertOptions) { c.Pub = pub @@ -63,21 +63,21 @@ func KeyPair(pub ed25519.PublicKey, priv ed25519.PrivateKey) CertOption { } } -// SerialNumber is the Certificate Serial number +// SerialNumber is the Certificate Serial number. func SerialNumber(serial *big.Int) CertOption { return func(c *CertOptions) { c.SerialNumber = serial } } -// NotBefore is the time the certificate is not valid before +// NotBefore is the time the certificate is not valid before. func NotBefore(time time.Time) CertOption { return func(c *CertOptions) { c.NotBefore = time } } -// NotAfter is the time the certificate is not valid after +// NotAfter is the time the certificate is not valid after. func NotAfter(time time.Time) CertOption { return func(c *CertOptions) { c.NotAfter = time diff --git a/util/pki/pki.go b/util/pki/pki.go index c4ac6f96a3..23a0039973 100644 --- a/util/pki/pki.go +++ b/util/pki/pki.go @@ -12,12 +12,12 @@ import ( "github.com/pkg/errors" ) -// GenerateKey returns an ed25519 key +// GenerateKey returns an ed25519 key. func GenerateKey() (ed25519.PublicKey, ed25519.PrivateKey, error) { return ed25519.GenerateKey(rand.Reader) } -// CA generates a self signed CA and returns cert, key in PEM format +// CA generates a self signed CA and returns cert, key in PEM format. func CA(opts ...CertOption) ([]byte, []byte, error) { opts = append(opts, IsCA()) options := CertOptions{} @@ -59,7 +59,7 @@ func CA(opts ...CertOption) ([]byte, []byte, error) { return cert.Bytes(), key.Bytes(), nil } -// CSR generates a certificate request in PEM format +// CSR generates a certificate request in PEM format. func CSR(opts ...CertOption) ([]byte, error) { options := CertOptions{} for _, o := range opts { @@ -83,7 +83,7 @@ func CSR(opts ...CertOption) ([]byte, error) { return out.Bytes(), nil } -// Sign decodes a CSR and signs it with the CA +// Sign decodes a CSR and signs it with the CA. func Sign(CACrt, CAKey, CSR []byte, opts ...CertOption) ([]byte, error) { options := CertOptions{} for _, o := range opts { diff --git a/util/pool/default.go b/util/pool/default.go index 90cad2f42f..749b3b9ef9 100644 --- a/util/pool/default.go +++ b/util/pool/default.go @@ -44,7 +44,7 @@ func (p *pool) Close() error { return nil } -// NoOp the Close since we manage it +// NoOp the Close since we manage it. func (p *poolConn) Close() error { return nil } diff --git a/util/pool/pool.go b/util/pool/pool.go index 1dfee597ce..c9240c8955 100644 --- a/util/pool/pool.go +++ b/util/pool/pool.go @@ -7,7 +7,7 @@ import ( "go-micro.dev/v4/transport" ) -// Pool is an interface for connection pooling +// Pool is an interface for connection pooling. type Pool interface { // Close the pool Close() error diff --git a/util/qson/qson.go b/util/qson/qson.go index eaf1cba4e8..ba93b61070 100644 --- a/util/qson/qson.go +++ b/util/qson/qson.go @@ -138,7 +138,7 @@ func queryToMap(param string) (map[string]interface{}, error) { // buildNewKey will take something like: // origKey = "bar[one][two]" // pieces = [bar one two ] -// and return "one[two]" +// and return "one[two]". func buildNewKey(origKey string) string { pieces := bracketSplitter.Split(origKey, -1) ret := origKey[len(pieces[0])+1:] diff --git a/util/registry/util.go b/util/registry/util.go index 7194bf0357..864079e542 100644 --- a/util/registry/util.go +++ b/util/registry/util.go @@ -52,7 +52,7 @@ func delNodes(old, del []*registry.Node) []*registry.Node { return nodes } -// CopyService make a copy of service +// CopyService make a copy of service. func CopyService(service *registry.Service) *registry.Service { // copy service s := new(registry.Service) @@ -78,7 +78,7 @@ func CopyService(service *registry.Service) *registry.Service { return s } -// Copy makes a copy of services +// Copy makes a copy of services. func Copy(current []*registry.Service) []*registry.Service { services := make([]*registry.Service, len(current)) for i, service := range current { @@ -87,7 +87,7 @@ func Copy(current []*registry.Service) []*registry.Service { return services } -// Merge merges two lists of services and returns a new copy +// Merge merges two lists of services and returns a new copy. func Merge(olist []*registry.Service, nlist []*registry.Service) []*registry.Service { var srv []*registry.Service @@ -119,7 +119,7 @@ func Merge(olist []*registry.Service, nlist []*registry.Service) []*registry.Ser return srv } -// Remove removes services and returns a new copy +// Remove removes services and returns a new copy. func Remove(old, del []*registry.Service) []*registry.Service { var services []*registry.Service diff --git a/util/ring/buffer.go b/util/ring/buffer.go index 45a7690a87..344c971c64 100644 --- a/util/ring/buffer.go +++ b/util/ring/buffer.go @@ -8,7 +8,7 @@ import ( "github.com/google/uuid" ) -// Buffer is ring buffer +// Buffer is ring buffer. type Buffer struct { size int @@ -17,13 +17,13 @@ type Buffer struct { streams map[string]*Stream } -// Entry is ring buffer data entry +// Entry is ring buffer data entry. type Entry struct { Value interface{} Timestamp time.Time } -// Stream is used to stream the buffer +// Stream is used to stream the buffer. type Stream struct { // Id of the stream Id string @@ -33,7 +33,7 @@ type Stream struct { Stop chan bool } -// Put adds a new value to ring buffer +// Put adds a new value to ring buffer. func (b *Buffer) Put(v interface{}) { b.Lock() defer b.Unlock() @@ -61,7 +61,7 @@ func (b *Buffer) Put(v interface{}) { } } -// Get returns the last n entries +// Get returns the last n entries. func (b *Buffer) Get(n int) []*Entry { b.RLock() defer b.RUnlock() @@ -78,7 +78,7 @@ func (b *Buffer) Get(n int) []*Entry { return b.vals[delta:] } -// Return the entries since a specific time +// Return the entries since a specific time. func (b *Buffer) Since(t time.Time) []*Entry { b.RLock() defer b.RUnlock() @@ -107,7 +107,7 @@ func (b *Buffer) Since(t time.Time) []*Entry { } // Stream logs from the buffer -// Close the channel when you want to stop +// Close the channel when you want to stop. func (b *Buffer) Stream() (<-chan *Entry, chan bool) { b.Lock() defer b.Unlock() @@ -125,12 +125,12 @@ func (b *Buffer) Stream() (<-chan *Entry, chan bool) { return entries, stop } -// Size returns the size of the ring buffer +// Size returns the size of the ring buffer. func (b *Buffer) Size() int { return b.size } -// New returns a new buffer of the given size +// New returns a new buffer of the given size. func New(i int) *Buffer { return &Buffer{ size: i, diff --git a/util/signal/signal.go b/util/signal/signal.go index bb5b7492bd..2ce801e01f 100644 --- a/util/signal/signal.go +++ b/util/signal/signal.go @@ -5,7 +5,7 @@ import ( "syscall" ) -// ShutDownSingals returns all the singals that are being watched for to shut down services. +// ShutDownSingals returns all the signals that are being watched for to shut down services. func Shutdown() []os.Signal { return []os.Signal{ syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGKILL, diff --git a/util/socket/pool.go b/util/socket/pool.go index 8ee2afb458..e2125dc0b1 100644 --- a/util/socket/pool.go +++ b/util/socket/pool.go @@ -44,7 +44,7 @@ func (p *Pool) Release(s *Socket) { delete(p.pool, s.id) } -// Close the pool and delete all the sockets +// Close the pool and delete all the sockets. func (p *Pool) Close() { p.Lock() defer p.Unlock() @@ -54,7 +54,7 @@ func (p *Pool) Close() { } } -// NewPool returns a new socket pool +// NewPool returns a new socket pool. func NewPool() *Pool { return &Pool{ pool: make(map[string]*Socket), diff --git a/util/socket/socket.go b/util/socket/socket.go index 0c5c27ffd9..03e4b6b8f9 100644 --- a/util/socket/socket.go +++ b/util/socket/socket.go @@ -7,7 +7,7 @@ import ( "go-micro.dev/v4/transport" ) -// Socket is our pseudo socket for transport.Socket +// Socket is our pseudo socket for transport.Socket. type Socket struct { id string // closed @@ -30,7 +30,7 @@ func (s *Socket) SetRemote(r string) { s.remote = r } -// Accept passes a message to the socket which will be processed by the call to Recv +// Accept passes a message to the socket which will be processed by the call to Recv. func (s *Socket) Accept(m *transport.Message) error { select { case s.recv <- m: @@ -40,7 +40,7 @@ func (s *Socket) Accept(m *transport.Message) error { } } -// Process takes the next message off the send queue created by a call to Send +// Process takes the next message off the send queue created by a call to Send. func (s *Socket) Process(m *transport.Message) error { select { case msg := <-s.send: @@ -91,7 +91,7 @@ func (s *Socket) Recv(m *transport.Message) error { return nil } -// Close closes the socket +// Close closes the socket. func (s *Socket) Close() error { select { case <-s.closed: diff --git a/util/stream/stream.go b/util/stream/stream.go index c4f89bf895..61cc2170e7 100644 --- a/util/stream/stream.go +++ b/util/stream/stream.go @@ -75,7 +75,7 @@ func (s *stream) Error() error { } // New returns a new encapsulated stream -// Proto stream within a server.Stream +// Proto stream within a server.Stream. func New(service, endpoint string, req interface{}, s Stream) server.Stream { return &stream{ Stream: s, diff --git a/util/sync/manager.go b/util/sync/manager.go index 6d24247e04..051e1605f1 100644 --- a/util/sync/manager.go +++ b/util/sync/manager.go @@ -15,7 +15,7 @@ type operation struct { maxiumum int } -// action represents the type of a queued operation +// action represents the type of a queued operation. type action int const ( diff --git a/util/sync/options.go b/util/sync/options.go index 87da70de2e..01dafd4b0a 100644 --- a/util/sync/options.go +++ b/util/sync/options.go @@ -6,7 +6,7 @@ import ( "go-micro.dev/v4/store" ) -// Options represents Sync options +// Options represents Sync options. type Options struct { // Stores represents layers in the sync in ascending order. L0, L1, L2, etc Stores []store.Store @@ -16,10 +16,10 @@ type Options struct { SyncMultiplier int64 } -// Option sets Sync Options +// Option sets Sync Options. type Option func(o *Options) -// Stores sets the layers that make up the sync +// Stores sets the layers that make up the sync. func Stores(stores ...store.Store) Option { return func(o *Options) { o.Stores = make([]store.Store, len(stores)) @@ -29,14 +29,14 @@ func Stores(stores ...store.Store) Option { } } -// SyncInterval sets the duration between syncs from L0 to L1 +// SyncInterval sets the duration between syncs from L0 to L1. func SyncInterval(d time.Duration) Option { return func(o *Options) { o.SyncInterval = d } } -// SyncMultiplier sets the multiplication factor for time to wait each sync layer +// SyncMultiplier sets the multiplication factor for time to wait each sync layer. func SyncMultiplier(i int64) Option { return func(o *Options) { o.SyncMultiplier = i diff --git a/util/sync/sync.go b/util/sync/sync.go index 6546863069..14fb3d8eec 100644 --- a/util/sync/sync.go +++ b/util/sync/sync.go @@ -11,7 +11,7 @@ import ( "go-micro.dev/v4/store" ) -// Sync implements a sync in for stores +// Sync implements a sync in for stores. type Sync interface { // Implements the store interface store.Store @@ -27,7 +27,7 @@ type syncStore struct { sync.RWMutex } -// NewSync returns a new Sync +// NewSync returns a new Sync. func NewSync(opts ...Option) Sync { c := &syncStore{} for _, o := range opts { @@ -46,7 +46,6 @@ func (c *syncStore) Close() error { return nil } -// Init initialises the storeOptions func (c *syncStore) Init(opts ...store.Option) error { for _, o := range opts { o(&c.storeOpts) @@ -55,7 +54,7 @@ func (c *syncStore) Init(opts ...store.Option) error { return errors.New("the sync has no stores") } if c.storeOpts.Context == nil { - return errors.New("please provide a context to the sync. Cancelling the context signals that the sync is being disposed and syncs the sync") + return errors.New("please provide a context to the sync. Canceling the context signals that the sync is being disposed and syncs the sync") } for _, s := range c.syncOpts.Stores { if err := s.Init(); err != nil { @@ -73,12 +72,12 @@ func (c *syncStore) Init(opts ...store.Option) error { return nil } -// Options returns the sync's store options +// Options returns the sync's store options. func (c *syncStore) Options() store.Options { return c.storeOpts } -// String returns a printable string describing the sync +// String returns a printable string describing the sync. func (c *syncStore) String() string { backends := make([]string, len(c.syncOpts.Stores)) for i, s := range c.syncOpts.Stores { @@ -99,7 +98,7 @@ func (c *syncStore) Write(r *store.Record, opts ...store.WriteOption) error { return c.syncOpts.Stores[0].Write(r, opts...) } -// Delete removes a key from the sync +// Delete removes a key from the sync. func (c *syncStore) Delete(key string, opts ...store.DeleteOption) error { return c.syncOpts.Stores[0].Delete(key, opts...) } diff --git a/util/test/test.go b/util/test/test.go index 043321fcec..54aa14edd2 100644 --- a/util/test/test.go +++ b/util/test/test.go @@ -5,7 +5,7 @@ import ( ) var ( - // mock registry data + // mock registry data. Data = map[string][]*registry.Service{ "foo": { { diff --git a/util/wrapper/wrapper.go b/util/wrapper/wrapper.go index 884ed64ef3..e20405afdc 100644 --- a/util/wrapper/wrapper.go +++ b/util/wrapper/wrapper.go @@ -43,7 +43,7 @@ func (f *fromServiceWrapper) Publish(ctx context.Context, p client.Message, opts return f.Client.Publish(ctx, p, opts...) } -// FromService wraps a client to inject service and auth metadata +// FromService wraps a client to inject service and auth metadata. func FromService(name string, c client.Client) client.Client { return &fromServiceWrapper{ c, @@ -53,7 +53,7 @@ func FromService(name string, c client.Client) client.Client { } } -// HandlerStats wraps a server handler to generate request/error stats +// HandlerStats wraps a server handler to generate request/error stats. func HandlerStats(stats stats.Stats) server.HandlerWrapper { // return a handler wrapper return func(h server.HandlerFunc) server.HandlerFunc { @@ -91,7 +91,7 @@ func (c *traceWrapper) Call(ctx context.Context, req client.Request, rsp interfa return err } -// TraceCall is a call tracing wrapper +// TraceCall is a call tracing wrapper. func TraceCall(name string, t trace.Tracer, c client.Client) client.Client { return &traceWrapper{ name: name, @@ -100,7 +100,7 @@ func TraceCall(name string, t trace.Tracer, c client.Client) client.Client { } } -// TraceHandler wraps a server handler to perform tracing +// TraceHandler wraps a server handler to perform tracing. func TraceHandler(t trace.Tracer) server.HandlerWrapper { // return a handler wrapper return func(h server.HandlerFunc) server.HandlerFunc { diff --git a/web/options.go b/web/options.go index cde3372012..a87ff08269 100644 --- a/web/options.go +++ b/web/options.go @@ -12,7 +12,7 @@ import ( "go-micro.dev/v4/registry" ) -// Options for web +// Options for web. type Options struct { Name string Version string @@ -79,14 +79,14 @@ func newOptions(opts ...Option) Options { return opt } -// Name of Web +// Name of Web. func Name(n string) Option { return func(o *Options) { o.Name = n } } -// Icon specifies an icon url to load in the UI +// Icon specifies an icon url to load in the UI. func Icon(ico string) Option { return func(o *Options) { if o.Metadata == nil { @@ -96,35 +96,35 @@ func Icon(ico string) Option { } } -// Id for Unique server id +// Id for Unique server id. func Id(id string) Option { return func(o *Options) { o.Id = id } } -// Version of the service +// Version of the service. func Version(v string) Option { return func(o *Options) { o.Version = v } } -// Metadata associated with the service +// Metadata associated with the service. func Metadata(md map[string]string) Option { return func(o *Options) { o.Metadata = md } } -// Address to bind to - host:port +// Address to bind to - host:port. func Address(a string) Option { return func(o *Options) { o.Address = a } } -// Advertise The address to advertise for discovery - host:port +// Advertise The address to advertise for discovery - host:port. func Advertise(a string) Option { return func(o *Options) { o.Advertise = a @@ -140,42 +140,42 @@ func Context(ctx context.Context) Option { } } -// Registry used for discovery +// Registry used for discovery. func Registry(r registry.Registry) Option { return func(o *Options) { o.Registry = r } } -// RegisterTTL Register the service with a TTL +// RegisterTTL Register the service with a TTL. func RegisterTTL(t time.Duration) Option { return func(o *Options) { o.RegisterTTL = t } } -// RegisterInterval Register the service with at interval +// RegisterInterval Register the service with at interval. func RegisterInterval(t time.Duration) Option { return func(o *Options) { o.RegisterInterval = t } } -// Handler for custom handler +// Handler for custom handler. func Handler(h http.Handler) Option { return func(o *Options) { o.Handler = h } } -// Server for custom Server +// Server for custom Server. func Server(srv *http.Server) Option { return func(o *Options) { o.Server = srv } } -// MicroService sets the micro.Service used internally +// MicroService sets the micro.Service used internally. func MicroService(s micro.Service) Option { return func(o *Options) { o.Service = s @@ -224,7 +224,7 @@ func AfterStop(fn func() error) Option { } } -// Secure Use secure communication. If TLSConfig is not specified we use InsecureSkipVerify and generate a self signed cert +// Secure Use secure communication. If TLSConfig is not specified we use InsecureSkipVerify and generate a self signed cert. func Secure(b bool) Option { return func(o *Options) { o.Secure = b @@ -238,14 +238,14 @@ func TLSConfig(t *tls.Config) Option { } } -// StaticDir sets the static file directory. This defaults to ./html +// StaticDir sets the static file directory. This defaults to ./html. func StaticDir(d string) Option { return func(o *Options) { o.StaticDir = d } } -// RegisterCheck run func before registry service +// RegisterCheck run func before registry service. func RegisterCheck(fn func(context.Context) error) Option { return func(o *Options) { o.RegisterCheck = fn @@ -261,7 +261,7 @@ func HandleSignal(b bool) Option { } } -// Logger sets the underline logger +// Logger sets the underline logger. func Logger(l logger.Logger) Option { return func(o *Options) { o.Logger = l diff --git a/web/service.go b/web/service.go index 48c45b02e1..b8fdf60cf6 100644 --- a/web/service.go +++ b/web/service.go @@ -337,7 +337,6 @@ func (s *service) Handle(pattern string, handler http.Handler) { } func (s *service) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) { - var seen bool s.RLock() for _, ep := range s.srv.Endpoints { @@ -523,7 +522,7 @@ func (s *service) Run() error { return s.stop() } -// Options returns the options for the given service +// Options returns the options for the given service. func (s *service) Options() Options { return s.opts } diff --git a/web/service_test.go b/web/service_test.go index 4457c12f1a..f6967a8f79 100644 --- a/web/service_test.go +++ b/web/service_test.go @@ -154,7 +154,6 @@ func TestService(t *testing.T) { t.Errorf("unexpected %s: want true, have false", tt.subject) } } - } func TestOptions(t *testing.T) { @@ -295,5 +294,4 @@ func TestTLS(t *testing.T) { t.Logf("service.Run() survived a client request without an error") } } - } diff --git a/web/web.go b/web/web.go index 674e9560bd..2dd8e8129d 100644 --- a/web/web.go +++ b/web/web.go @@ -9,7 +9,7 @@ import ( "github.com/google/uuid" ) -// Service is a web service with service discovery built in +// Service is a web service with service discovery built in. type Service interface { Client() *http.Client Init(opts ...Option) error @@ -21,27 +21,27 @@ type Service interface { Run() error } -// Option for web +// Option for web. type Option func(o *Options) -// Web basic Defaults +// Web basic Defaults. var ( - // For serving + // For serving. DefaultName = "go-web" DefaultVersion = "latest" DefaultId = uuid.New().String() DefaultAddress = ":0" - // for registration + // for registration. DefaultRegisterTTL = time.Second * 90 DefaultRegisterInterval = time.Second * 30 - // static directory + // static directory. DefaultStaticDir = "html" DefaultRegisterCheck = func(context.Context) error { return nil } ) -// NewService returns a new web.Service +// NewService returns a new web.Service. func NewService(opts ...Option) Service { return newService(opts...) } diff --git a/web/web_test.go b/web/web_test.go index 738ead84b9..3eb1b86905 100644 --- a/web/web_test.go +++ b/web/web_test.go @@ -48,7 +48,7 @@ func testFunc() { web.Context(ctx), web.HandleSignal(false), ) - //s.Init() + // s.Init() //w.Init() var wg sync.WaitGroup