Skip to content

Commit

Permalink
fix: some linting issues (#2563)
Browse files Browse the repository at this point in the history
  • Loading branch information
Davincible authored Sep 30, 2022
1 parent 47e6a8d commit 85c0b0b
Show file tree
Hide file tree
Showing 221 changed files with 1,025 additions and 1,283 deletions.
5 changes: 3 additions & 2 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -182,6 +182,7 @@ linters:
- nonamedreturns
- makezero
- gofumpt
- nlreturn

# Can be considered to be enabled
- gochecknoinits
Expand Down
27 changes: 15 additions & 12 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -29,16 +29,18 @@ type Api interface {
String() string
}

// Options are API options.
type Options struct {
// Address of the server
Address string
// Router for resolving routes
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
Expand All @@ -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
Expand All @@ -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)
Expand All @@ -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
Expand All @@ -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")
Expand Down Expand Up @@ -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...)
}
1 change: 0 additions & 1 deletion api/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,5 +148,4 @@ func TestValidate(t *testing.T) {
if err := Validate(epPcreInvalid); err == nil {
t.Fatalf("invalid pcre %v", epPcreInvalid.Path[0])
}

}
47 changes: 31 additions & 16 deletions api/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"`
Expand All @@ -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{
Expand Down Expand Up @@ -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=="}
Expand All @@ -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
}
Expand All @@ -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
}
Expand All @@ -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
Expand All @@ -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)
}

Expand Down
7 changes: 3 additions & 4 deletions api/default.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,25 +45,24 @@ func newApi(opts ...Option) Api {
}
}

// Initialise options
func (a *api) Init(opts ...Option) error {
for _, o := range opts {
o(&a.options)
}
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
}
Expand Down
2 changes: 1 addition & 1 deletion api/handler/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
8 changes: 4 additions & 4 deletions api/handler/api/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
)

Expand All @@ -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":
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion api/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions api/handler/http/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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...)

Expand Down
2 changes: 1 addition & 1 deletion api/handler/http/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
Loading

0 comments on commit 85c0b0b

Please sign in to comment.