Skip to content

Commit

Permalink
Chore: Add .golangci.yaml file
Browse files Browse the repository at this point in the history
- added .golangci.yaml file
Signed-off-by: Tanryberdi <tanryberdi@gmail.com>

See vaguecoder#4
  • Loading branch information
tanryberdi committed Jan 11, 2023
1 parent 609264b commit e5d9dec
Show file tree
Hide file tree
Showing 10 changed files with 104 additions and 25 deletions.
63 changes: 63 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
run:
timeout: 3m

linters-settings:
cyclop:
max-complexity: 30
nolintlint:
allow-unused: true

linters:
disable-all: true
enable:
- gosimple # specializes in simplifying a code
- govet # reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
- ineffassign # detects when assignments to existing variables are not used
- staticcheck # is a go vet on steroids, applying a ton of static analysis checks
- typecheck # like the front-end of a Go compiler, parses and type-checks Go code
- unused # checks for unused constants, variables, functions and types
- asasalint # checks for pass []any as any in variadic func(...any)
- asciicheck # checks that your code does not contain non-ASCII identifiers
- bidichk # checks for dangerous unicode character sequences
- bodyclose # checks whether HTTP response body is closed successfully
- cyclop # checks function and package cyclomatic complexity
- dupl # tool for code clone detection
- durationcheck # checks for two durations multiplied together
- errname # checks that sentinel errors are prefixed with the Err and error types are suffixed with the Error
- execinquery # checks query string in Query function which reads your Go src files and warning it finds
- exhaustive # checks exhaustiveness of enum switch statements
- exportloopref # checks for pointers to enclosing loop variables
- forbidigo # forbids identifiers
- gochecknoinits # checks that no init functions are present in Go code
- gocyclo # computes and checks the cyclomatic complexity of functions
- goimports # in addition to fixing imports, goimports also formats your code in the same style as gofmt
- gomodguard # allow and block lists linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations
- goprintffuncname # checks that printf-like functions are named with f at the end
- gosec # inspects source code for security problems
- loggercheck # checks key value pairs for common logger libraries (kitlog,klog,logr,zap)
- makezero # finds slice declarations with non-zero initial length
- nakedret # finds naked returns in functions greater than a specified function length
- nilerr # finds the code that returns nil even if it checks that the error is not nil
- nilnil # checks that there is no simultaneous return of nil error and an invalid value
- noctx # finds sending http request without context.Context
- nolintlint # reports ill-formed or insufficient nolint directives
- nonamedreturns # reports all named returns
- nosprintfhostport # checks for misuse of Sprintf to construct a host with port in a URL
- predeclared # finds code that shadows one of Go's predeclared identifiers
- promlinter # checks Prometheus metrics naming via promlint
- reassign # checks that package variables are not reassigned
- revive # fast, configurable, extensible, flexible, and beautiful linter for Go, drop-in replacement of golint
- rowserrcheck # checks whether Err of rows is checked successfully
- sqlclosecheck # checks that sql.Rows and sql.Stmt are closed
- stylecheck # is a replacement for golint
- tenv # detects using os.Setenv instead of t.Setenv since Go1.17
- unconvert # removes unnecessary type conversions
- wastedassign # finds wasted assignment statements
- whitespace # detects leading and trailing whitespace

issues:
exclude-rules:
- path: "_test\\.go"
linters:
- bodyclose
- noctx
4 changes: 4 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
lint:
@echo "Linting ...Please make sure you are on golangci-lint v1.50.0 or later:\n\tgo install github.com/golangci/golangci-lint/cmd/golangci-lint@latest\n"
@golangci-lint run --timeout=5m

test:
@echo "Testing ..."
@go clean -testcache
Expand Down
15 changes: 12 additions & 3 deletions doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -239,13 +239,22 @@ as well:
"category", "technology",
"id", "42")
Mux supports the addition of middlewares to a Router, which are executed in the order they are added if a match is found, including its subrouters. Middlewares are (typically) small pieces of code which take one request, do something with it, and pass it down to another middleware or the final handler. Some common use cases for middleware are request logging, header manipulation, or ResponseWriter hijacking.
Mux supports the addition of middlewares to a Router, which are executed in the
order they are added if a match is found, including its subrouters. Middlewares
are (typically) small pieces of code which take one request, do something with
it, and pass it down to another middleware or the final handler. Some common use
cases for middleware are request logging, header manipulation, or ResponseWriter
hijacking.
type MiddlewareFunc func(http.Handler) http.Handler
Typically, the returned handler is a closure which does something with the http.ResponseWriter and http.Request passed to it, and then calls the handler passed as parameter to the MiddlewareFunc (closures can access variables from the context where they are created).
Typically, the returned handler is a closure which does something with the
http.ResponseWriter and http.Request passed to it, and then calls the handler
passed as parameter to the MiddlewareFunc (closures can access variables from
the context where they are created).
A very basic middleware which logs the URI of the request being handled could be written as:
A very basic middleware which logs the URI of the request being handled could be
written as:
func simpleMw(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand Down
6 changes: 3 additions & 3 deletions example_authentication_middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,20 @@ import (
mux "github.com/vaguecoder/gorilla-mux"
)

// Define our struct
// Define our struct.
type authenticationMiddleware struct {
tokenUsers map[string]string
}

// Initialize it somewhere
// Initialize it somewhere.
func (amw *authenticationMiddleware) Populate() {
amw.tokenUsers["00000000"] = "user0"
amw.tokenUsers["aaaaaaaa"] = "userA"
amw.tokenUsers["05f717e5"] = "randomUser"
amw.tokenUsers["deadbeef"] = "user0"
}

// Middleware function, which will be called for each request
// Middleware function, which will be called for each request.
func (amw *authenticationMiddleware) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("X-Session-Token")
Expand Down
14 changes: 7 additions & 7 deletions mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ type Router struct {
routeConf
}

// common route configuration shared between `Router` and `Route`
// common route configuration shared between `Router` and `Route`.
type routeConf struct {
// If true, "/path/foo%2Fbar/to" will match the path "/path/{var}/to"
useEncodedPath bool
Expand Down Expand Up @@ -180,7 +180,6 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
}
// Clean path to canonical form and redirect.
if p := cleanPath(path); p != path {

// Added 3 lines (Philip Schlump) - It was dropping the query string and #whatever from query.
// This matches with fix in go 1.2 r.c. 4 for same problem. Go Issue:
// http://code.google.com/p/go/issues/detail?id=5252
Expand Down Expand Up @@ -363,9 +362,9 @@ func (r *Router) Walk(walkFn WalkFunc) error {
return r.walk(walkFn, []*Route{})
}

// SkipRouter is used as a return value from WalkFuncs to indicate that the
// ErrSkipRouter is used as a return value from WalkFuncs to indicate that the
// router that walk is about to descend to should be skipped.
var SkipRouter = errors.New("skip this router")
var ErrSkipRouter = errors.New("skip this router")

// WalkFunc is the type of the function called for each route visited by Walk.
// At every invocation, it is given the current route, and the current router,
Expand All @@ -375,7 +374,7 @@ type WalkFunc func(route *Route, router *Router, ancestors []*Route) error
func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error {
for _, t := range r.routes {
err := walkFn(t, r, ancestors)
if err == SkipRouter {
if err == ErrSkipRouter {
continue
}
if err != nil {
Expand All @@ -384,7 +383,7 @@ func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error {
for _, sr := range t.matchers {
if h, ok := sr.(*Router); ok {
ancestors = append(ancestors, t)
err := h.walk(walkFn, ancestors)
err = h.walk(walkFn, ancestors)
if err != nil {
return err
}
Expand All @@ -393,7 +392,7 @@ func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error {
}
if h, ok := t.handler.(*Router); ok {
ancestors = append(ancestors, t)
err := h.walk(walkFn, ancestors)
err = h.walk(walkFn, ancestors)
if err != nil {
return err
}
Expand Down Expand Up @@ -524,6 +523,7 @@ func mapFromPairsToRegex(pairs ...string) (map[string]*regexp.Regexp, error) {
}
m := make(map[string]*regexp.Regexp, length/2)
for i := 0; i < length; i += 2 {
//nolint:govet // err is shadowed but regex was new
regex, err := regexp.Compile(pairs[i+1])
if err != nil {
return nil, err
Expand Down
11 changes: 7 additions & 4 deletions mux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ type routeTest struct {
}

func TestHost(t *testing.T) {

tests := []routeTest{
{
title: "Host route match",
Expand Down Expand Up @@ -1600,7 +1599,7 @@ func TestWalkSingleDepth(t *testing.T) {
err := r0.Walk(func(route *Route, router *Router, ancestors []*Route) error {
matcher := route.matchers[0].(*routeRegexp)
if matcher.template == "/d" {
return SkipRouter
return ErrSkipRouter
}
if len(ancestors) != depths[i] {
t.Errorf(`Expected depth of %d at i = %d; got "%d"`, depths[i], i, len(ancestors))
Expand Down Expand Up @@ -1655,6 +1654,7 @@ func TestWalkNested(t *testing.T) {
t.Errorf(`Expected %s got %s`, path, tpl)
}
currWantAncestors := testCases[idx].ancestors
//nolint:govet // we need to discuss
if !reflect.DeepEqual(currWantAncestors, ancestors) {
t.Errorf(`Expected %+v got %+v`, currWantAncestors, ancestors)
}
Expand Down Expand Up @@ -1830,7 +1830,8 @@ func testRoute(t *testing.T, test routeTest) {
t.Fatalf("(%v) URLHost error: %v -- %v", test.title, err, getRouteTemplate(route))
}
if uri.Scheme != u.Scheme {
t.Errorf("(%v) URLHost scheme not equal: expected %v, got %v -- %v", test.title, uri.Scheme, u.Scheme, getRouteTemplate(route))
t.Errorf("(%v) URLHost scheme not equal: expected %v, "+
"got %v -- %v", test.title, uri.Scheme, u.Scheme, getRouteTemplate(route))
return
}
if uri.Host != u.Host {
Expand Down Expand Up @@ -1976,6 +1977,7 @@ func Test301Redirect(t *testing.T) {
}
r.ServeHTTP(&res, req)

//nolint:stylecheck // we need to discuss
if "http://localhost/api/?abc=def" != res.hh["Location"][0] {
t.Errorf("Should have complete URL with query string")
}
Expand Down Expand Up @@ -2436,7 +2438,8 @@ func testMethodsSubrouter(t *testing.T, test methodsSubrouterTest) {

case http.StatusMovedPermanently:
if gotLocation := resp.HeaderMap.Get("Location"); gotLocation != test.redirectTo {
t.Errorf("(%s) Expected %q route-match to redirect to %q, but got %q", test.title, test.method, test.redirectTo, gotLocation)
t.Errorf("(%s) Expected %q route-match to redirect to %q, "+
"but got %q", test.title, test.method, test.redirectTo, gotLocation)
}

case http.StatusOK:
Expand Down
1 change: 0 additions & 1 deletion old_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -522,7 +522,6 @@ func TestSchemeMatcher(t *testing.T) {
}

func TestUrlBuilding(t *testing.T) {

for _, v := range urlBuildingTests {
u, _ := v.route.URL(v.vars...)
url := u.String()
Expand Down
4 changes: 2 additions & 2 deletions regexp.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool {

// url builds a URL part using the given values.
func (r *routeRegexp) url(values map[string]string) (string, error) {
urlValues := make([]interface{}, len(r.varsN), len(r.varsN))
urlValues := make([]interface{}, len(r.varsN))
for k, v := range r.varsN {
value, ok := values[v]
if !ok {
Expand Down Expand Up @@ -239,7 +239,7 @@ func (r *routeRegexp) getURLQuery(req *http.Request) string {

// findFirstQueryKey returns the same result as (*url.URL).Query()[key][0].
// If key was not found, empty string and false is returned.
func findFirstQueryKey(rawQuery, key string) (value string, ok bool) {
func findFirstQueryKey(rawQuery, key string) (string, bool) {
query := []byte(rawQuery)
for len(query) > 0 {
foundKey := query
Expand Down
8 changes: 4 additions & 4 deletions regexp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ func Benchmark_findQueryKey(b *testing.B) {
all, _ := url.ParseQuery(query)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for key, _ := range all {
for index := 0; index < b.N; index++ {
for key := range all {
_, _ = findFirstQueryKey(query, key)
}
}
Expand All @@ -78,8 +78,8 @@ func Benchmark_findQueryKeyGoLib(b *testing.B) {
u.RawQuery = query
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for key, _ := range all {
for index := 0; index < b.N; index++ {
for key := range all {
v := u.Query()[key]
if len(v) > 0 {
_ = v[0]
Expand Down
3 changes: 2 additions & 1 deletion route.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ func (r *Route) Match(req *http.Request, match *RouteMatch) bool {
match.MatchErr = nil
}

matchErr = nil
// inefficient assignment
// matchErr = nil
return false
}
}
Expand Down

0 comments on commit e5d9dec

Please sign in to comment.