Skip to content

Commit

Permalink
feat: golangci-lint check
Browse files Browse the repository at this point in the history
  • Loading branch information
daheige committed May 15, 2022
1 parent e3246a7 commit 3c2c01c
Show file tree
Hide file tree
Showing 10 changed files with 167 additions and 36 deletions.
124 changes: 124 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
linters:
disable-all: true
enable:
- bodyclose
- deadcode
- depguard
- dogsled
- dupl
- errcheck
- exportloopref
- funlen
- gochecknoinits
- goconst
- gocritic
- gocyclo
- gofmt
- goimports
- gomnd
- goprintffuncname
- gosec
- gosimple
- govet
- ineffassign
- lll
- misspell
- nakedret
- noctx
- nolintlint
- staticcheck
- structcheck
- stylecheck
- typecheck
- unconvert
- unparam
- unused
- varcheck
- whitespace

linters-settings:
depguard:
list-type: blacklist
packages:
# logging is allowed only by logutils.Log, logrus
# is allowed to use only in logutils package
- github.com/sirupsen/logrus
packages-with-error-message:
- github.com/sirupsen/logrus: "logging is allowed only by logutils.Log"
dupl:
threshold: 100
funlen:
lines: 100
statements: 50
goconst:
min-len: 2
min-occurrences: 3
gocritic:
enabled-tags:
- diagnostic
- experimental
- opinionated
- performance
- style
disabled-checks:
- dupImport # https://github.com/go-critic/go-critic/issues/845
- ifElseChain
- octalLiteral
- whyNoLint
- wrapperFunc
gocyclo:
min-complexity: 15
goimports:
local-prefixes: github.com/golangci/golangci-lint
gomnd:
# don't include the "operation" and "assign"
checks:
- argument
- case
- condition
- return
ignored-numbers:
- '0'
- '1'
- '2'
- '3'
ignored-functions:
- strings.SplitN

govet:
check-shadowing: true
check-unreachable: true
check-rangeloops: true
check-copylocks: true
settings:
printf:
funcs:
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf
lll:
line-length: 140
misspell:
locale: US
nolintlint:
allow-leading-space: true # don't require machine-readable nolint directives (i.e. with no leading space)
allow-unused: false # report any unused nolint directives
require-explanation: false # don't require an explanation for nolint directives
require-specific: false # don't require nolint directives to be specific about which linter is being skipped

# output configuration options
output:
# colored-line-number|line-number|json|tab|checkstyle|code-climate, default is "colored-line-number"
format: colored-line-number

# print lines of code with issue, default is true
print-issued-lines: true

# print linter name in the end of issue text, default is true
print-linter-name: true

run:
timeout: 5m
skip-dirs:
- example
4 changes: 2 additions & 2 deletions ctx_keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ package gmicro
// CtxKey ctx key type.
type CtxKey string

const(
const (
// XRequestID request_id
XRequestID CtxKey = "x-request-id"
XRequestID CtxKey = "x-request-id"

// GRPCClientIP grpc client_ip
GRPCClientIP CtxKey = "grpc_client_ip"
Expand Down
1 change: 1 addition & 0 deletions docs/grpc-go/bin/docker-build.sh
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#!/usr/bin/env bash

#编译golang可执行文件
root_dir=$(cd "$(dirname "$0")"; cd ..; pwd)

Expand Down
18 changes: 16 additions & 2 deletions golangci-lint-check.sh
Original file line number Diff line number Diff line change
@@ -1,4 +1,18 @@
#!/bin/bash
go mod tidy
#!/usr/bin/env bash

goci=$(which "golangci-lint")
if [ -z $goci ]; then
echo "please install golangci-lint use cmd: go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest"
exit 0
fi

echo "current golangci-lint version"
golangci-lint version

echo "golangci-lint check begin"
go mod tidy
golangci-lint run ./... > golangci.log

echo "golangci check success,log write into golangci.log"

exit 0
14 changes: 5 additions & 9 deletions micro.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
"strings"
"time"

middleware "github.com/grpc-ecosystem/go-grpc-middleware"
gRecovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
gValidator "github.com/grpc-ecosystem/go-grpc-middleware/validator"
gPrometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
Expand Down Expand Up @@ -199,9 +198,8 @@ func NewService(opts ...Option) *Service {
s.mux = gRuntime.NewServeMux(s.muxOptions...)

s.gRPCServerOptions = append(s.gRPCServerOptions,
middleware.WithStreamServerChain(s.streamInterceptors...))
s.gRPCServerOptions = append(s.gRPCServerOptions,
middleware.WithUnaryServerChain(s.unaryInterceptors...))
grpc.ChainStreamInterceptor(s.streamInterceptors...),
grpc.ChainUnaryInterceptor(s.unaryInterceptors...))

s.GRPCServer = grpc.NewServer(
s.gRPCServerOptions...,
Expand Down Expand Up @@ -240,7 +238,6 @@ func (s *Service) RequestInterceptor(ctx context.Context, req interface{}, info

s.logger.Printf("exec begin\n")
s.logger.Printf("client_ip: %s\n", clientIP)
// s.logger.Printf("request: %v\n", req)

// request ctx key
if logID := ctx.Value(XRequestID); logID == nil {
Expand Down Expand Up @@ -283,7 +280,7 @@ func (s *Service) AddRoute(routes ...Route) {

// Start starts the microservice with listening on the ports
// start grpc gateway and http server on different port
func (s *Service) Start(httpPort int, grpcPort int) error {
func (s *Service) Start(httpPort, grpcPort int) error {
// http gw host and grpc host
s.httpServerAddress = fmt.Sprintf("0.0.0.0:%d", httpPort)
s.gRPCAddress = fmt.Sprintf("0.0.0.0:%d", grpcPort)
Expand Down Expand Up @@ -566,9 +563,8 @@ func NewServiceWithoutGateway(opts ...Option) *Service {
s.muxOptions = nil

s.gRPCServerOptions = append(s.gRPCServerOptions,
middleware.WithStreamServerChain(s.streamInterceptors...))
s.gRPCServerOptions = append(s.gRPCServerOptions,
middleware.WithUnaryServerChain(s.unaryInterceptors...))
grpc.ChainStreamInterceptor(s.streamInterceptors...),
grpc.ChainUnaryInterceptor(s.unaryInterceptors...))

s.GRPCServer = grpc.NewServer(
s.gRPCServerOptions...,
Expand Down
19 changes: 10 additions & 9 deletions micro_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"context"
"errors"
"fmt"
"io/ioutil"
"io"
"log"
"net"
"net/http"
Expand All @@ -13,9 +13,10 @@ import (
"time"

"github.com/daheige/gmicro/v2/example/pb"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
gRuntime "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)

var (
Expand All @@ -27,7 +28,7 @@ var (
func initConf() {
reverseProxyFunc = func(
ctx context.Context,
mux *runtime.ServeMux,
mux *gRuntime.ServeMux,
grpcHostAndPort string,
opts []grpc.DialOption,
) error {
Expand Down Expand Up @@ -152,7 +153,7 @@ func TestNewService(t *testing.T) {
resp, err = client.Get(fmt.Sprintf("http://127.0.0.1:%d/health", httpPort))
should.NoError(err)
should.Equal(http.StatusOK, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
should.NoError(err)
should.Equal("OK", string(b))

Expand Down Expand Up @@ -199,8 +200,8 @@ func TestNewService(t *testing.T) {
s4.AddHandlerFromEndpoint(reverseProxyFunc)

go func() {
err := s4.Start(httpPort, grpcPort)
should.NoError(err)
e := s4.Start(httpPort, grpcPort)
should.NoError(e)
}()

// wait 1 second for the server start
Expand Down Expand Up @@ -234,7 +235,7 @@ func TestErrorReverseProxyFunc(t *testing.T) {
errText := "reverse proxy func error"
reverseProxyFunc = func(
ctx context.Context,
mux *runtime.ServeMux,
mux *gRuntime.ServeMux,
grpcHostAndPort string,
opts []grpc.DialOption,
) error {
Expand Down Expand Up @@ -377,7 +378,7 @@ func TestGRPCAndHttpServer(t *testing.T) {
resp, err = client.Get(fmt.Sprintf("http://127.0.0.1:%d/health", sharePort))
should.NoError(err)
should.Equal(http.StatusOK, resp.StatusCode)
b, err := ioutil.ReadAll(resp.Body)
b, err := io.ReadAll(resp.Body)
should.NoError(err)
should.Equal("OK", string(b))

Expand Down Expand Up @@ -436,7 +437,7 @@ func TestGRPCServerWithoutGateway(t *testing.T) {
should.Error(err)

// Set up a connection to the server.
conn, err := grpc.Dial(s.gRPCAddress, grpc.WithInsecure())
conn, err := grpc.Dial(s.gRPCAddress, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf("did not connect: %v", err)
}
Expand Down
3 changes: 1 addition & 2 deletions option.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"os"
"time"

"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
gRuntime "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc"
)
Expand Down Expand Up @@ -121,7 +120,7 @@ func WithGRPCDialOption(dialOption ...grpc.DialOption) Option {
}

// WithMuxOption returns an Option to append a mux option
func WithMuxOption(muxOption ...runtime.ServeMuxOption) Option {
func WithMuxOption(muxOption ...gRuntime.ServeMuxOption) Option {
return func(s *Service) {
s.muxOptions = append(s.muxOptions, muxOption...)
}
Expand Down
8 changes: 4 additions & 4 deletions option_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"testing"
"time"

"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
gRuntime "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/stretchr/testify/assert"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
Expand Down Expand Up @@ -100,9 +100,9 @@ func TestWithHTTPServer(t *testing.T) {

func TestMuxOption(t *testing.T) {
s := NewService(
WithMuxOption(runtime.WithMarshalerOption(
runtime.MIMEWildcard, &runtime.HTTPBodyMarshaler{
Marshaler: &runtime.JSONPb{
WithMuxOption(gRuntime.WithMarshalerOption(
gRuntime.MIMEWildcard, &gRuntime.HTTPBodyMarshaler{
Marshaler: &gRuntime.JSONPb{
MarshalOptions: protojson.MarshalOptions{
UseProtoNames: true,
EmitUnpopulated: true,
Expand Down
8 changes: 4 additions & 4 deletions router.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
package gmicro

import (
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
gRuntime "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/grpc-ecosystem/grpc-gateway/v2/utilities"
)

// Route represents the route for mux
type Route struct {
Method string
Path string
Handler runtime.HandlerFunc
Handler gRuntime.HandlerFunc
}

// AllPattern returns a pattern which matches any url
func AllPattern() runtime.Pattern {
return runtime.MustPattern(runtime.NewPattern(1, []int{int(utilities.OpPush), 0}, []string{""}, ""))
func AllPattern() gRuntime.Pattern {
return gRuntime.MustPattern(gRuntime.NewPattern(1, []int{int(utilities.OpPush), 0}, []string{""}, ""))
}
4 changes: 0 additions & 4 deletions test.json

This file was deleted.

0 comments on commit 3c2c01c

Please sign in to comment.