search
HomeBackend DevelopmentGolangHow to customize linter (static checking tool) in Go language

Preface

Usually we use static code checking tools to ensure code quality in business projects. Through static code checking tools we can discover some things in advance For problems such as undefined variables, type mismatches, variable scope problems, out-of-bounds array subscripts, memory leaks, etc., the tool will classify the severity of the problem according to its own rules, give different labels and prompts, and static code inspection To help us find problems as early as possible, the commonly used static code inspection tools in the Go language include golang-lint and golint. Some rules have been formulated in these tools. , although it can meet most scenarios, but sometimes we will encounter the need to make some customized rules for special scenarios, so in this article we will learn how to customize linter requirements;

How is static checking implemented in Go language?

As we all knowGo language is a compiled language. Compiled language is inseparable from the stages of lexical analysis, syntax analysis, semantic analysis, optimization, and compilation and linking. Those who have learned the principles of compilation Friends should be familiar with the following picture:

How to customize linter (static checking tool) in Go language

The compiler translates high-level language into machine language. It first performs lexical analysis on the source code. Lexical analysis is the process of converting character sequences into Token sequences. Token is generally divided into these categories: keywords, identifiers, literals (including numbers, strings), special symbols (such as plus signs, equal signs), and generates Token sequences Finally, syntax analysis is required. After further processing, a syntax tree with expressions as nodes is generated. This syntax tree is what we often call AST. During the process of generating the syntax tree, some For formal errors, such as missing parentheses, after the syntax analysis is completed, semantic analysis is required. Here, all static semantics that can be checked during compilation are checked. The subsequent process is intermediate code generation, target code generation and optimization, and linking. This is not the case here. Detailed description, the main purpose here is to introduce the abstract syntax tree (AST), Our static code inspection tool is to do it by analyzing the abstract syntax tree (AST) according to customized rules; then the abstract syntax tree is long What does it look like? We can use the go/ast, go/parser, go/token packages provided by the standard library to print out AST, or we can Use visualization tools: http://goast.yuroyoro.net/ View AST, we can see the example below for what AST looks like;

Develop linter rules

Suppose we now want to develop such a code specification in our team. The first parameter type of all functions must be Context, no We must give a warning if it conforms to this specification; OK, now that the rules have been set, let’s find a way to implement it; first let’s take a problematic example:

// example.go
package main

func add(a, b int) int {
 return a + b
}

corresponds to ASTAs follows:

*ast.FuncDecl {
     8  .  .  .  Name: *ast.Ident {
     9  .  .  .  .  NamePos: 3:6
    10  .  .  .  .  Name: "add" 
    11  .  .  .  .  Obj: *ast.Object {
    12  .  .  .  .  .  Kind: func
    13  .  .  .  .  .  Name: "add" // 函数名
    14  .  .  .  .  .  Decl: *(obj @ 7)
    15  .  .  .  .  }
    16  .  .  .  }
    17  .  .  .  Type: *ast.FuncType {
    18  .  .  .  .  Func: 3:1
    19  .  .  .  .  Params: *ast.FieldList {
    20  .  .  .  .  .  Opening: 3:9
    21  .  .  .  .  .  List: []*ast.Field (len = 1) {
    22  .  .  .  .  .  .  0: *ast.Field {
    23  .  .  .  .  .  .  .  Names: []*ast.Ident (len = 2) {
    24  .  .  .  .  .  .  .  .  0: *ast.Ident {
    25  .  .  .  .  .  .  .  .  .  NamePos: 3:10
    26  .  .  .  .  .  .  .  .  .  Name: "a"
    27  .  .  .  .  .  .  .  .  .  Obj: *ast.Object {
    28  .  .  .  .  .  .  .  .  .  .  Kind: var
    29  .  .  .  .  .  .  .  .  .  .  Name: "a"
    30  .  .  .  .  .  .  .  .  .  .  Decl: *(obj @ 22)
    31  .  .  .  .  .  .  .  .  .  }
    32  .  .  .  .  .  .  .  .  }
    33  .  .  .  .  .  .  .  .  1: *ast.Ident {
    34  .  .  .  .  .  .  .  .  .  NamePos: 3:13
    35  .  .  .  .  .  .  .  .  .  Name: "b"
    36  .  .  .  .  .  .  .  .  .  Obj: *ast.Object {
    37  .  .  .  .  .  .  .  .  .  .  Kind: var
    38  .  .  .  .  .  .  .  .  .  .  Name: "b"
    39  .  .  .  .  .  .  .  .  .  .  Decl: *(obj @ 22)
    40  .  .  .  .  .  .  .  .  .  }
    41  .  .  .  .  .  .  .  .  }
    42  .  .  .  .  .  .  .  }
    43  .  .  .  .  .  .  .  Type: *ast.Ident {
    44  .  .  .  .  .  .  .  .  NamePos: 3:15
    45  .  .  .  .  .  .  .  .  Name: "int" // 参数名
    46  .  .  .  .  .  .  .  }
    47  .  .  .  .  .  .  }
    48  .  .  .  .  .  }
    49  .  .  .  .  .  Closing: 3:18
    50  .  .  .  .  }
    51  .  .  .  .  Results: *ast.FieldList {
    52  .  .  .  .  .  Opening: -
    53  .  .  .  .  .  List: []*ast.Field (len = 1) {
    54  .  .  .  .  .  .  0: *ast.Field {
    55  .  .  .  .  .  .  .  Type: *ast.Ident {
    56  .  .  .  .  .  .  .  .  NamePos: 3:20
    57  .  .  .  .  .  .  .  .  Name: "int"
    58  .  .  .  .  .  .  .  }
    59  .  .  .  .  .  .  }
    60  .  .  .  .  .  }
    61  .  .  .  .  .  Closing: -
    62  .  .  .  .  }
    63  .  .  .  }

Method 1: Standard library implements custom linter

Through the above AST structure we can find where the function parameter type is Structurally, because we can write the parsing code based on this structure as follows:

package main

import (
 "fmt"
 "go/ast"
 "go/parser"
 "go/token"
 "log"
 "os"
)

func main() {
 v := visitor{fset: token.NewFileSet()}
 for _, filePath := range os.Args[1:] {
  if filePath == "--" { // to be able to run this like "go run main.go -- input.go"
   continue
  }

  f, err := parser.ParseFile(v.fset, filePath, nil, 0)
  if err != nil {
   log.Fatalf("Failed to parse file %s: %s", filePath, err)
  }
  ast.Walk(&v, f)
 }
}

type visitor struct {
 fset *token.FileSet
}

func (v *visitor) Visit(node ast.Node) ast.Visitor {
 funcDecl, ok := node.(*ast.FuncDecl)
 if !ok {
  return v
 }

 params := funcDecl.Type.Params.List // get params
 // list is equal of zero that don't need to checker.
 if len(params) == 0 {
  return v
 }

 firstParamType, ok := params[0].Type.(*ast.SelectorExpr)
 if ok && firstParamType.Sel.Name == "Context" {
  return v
 }

 fmt.Printf("%s: %s function first params should be Context\n",
  v.fset.Position(node.Pos()), funcDecl.Name.Name)
 return v
}

Then execute the command as follows:

$ go run ./main.go -- ./example.go
./example.go:3:1: add function first params should be Context

We can see through the output that the function add()The first parameter must be Context; this is a simple implementation, because the structure of AST is a bit complicated, so I won’t introduce each structure in detail here. You can see Cao An article I wrote before: golang and ast

方式二:go/analysis

看过上面代码的朋友肯定有点抓狂了,有很多实体存在,要开发一个linter,我们需要搞懂好多实体,好在go/analysis进行了封装,go/analysislinter 提供了统一的接口,它简化了与IDE,metalinters,代码Review等工具的集成。如,任何go/analysislinter都可以高效的被go vet执行,下面我们通过代码方式来介绍go/analysis的优势;

新建一个项目代码结构如下:

.
├── firstparamcontext
│   └── firstparamcontext.go
├── go.mod
├── go.sum
└── testfirstparamcontext
    ├── example.go
    └── main.go

添加检查模块代码,在firstparamcontext.go添加如下代码:

package firstparamcontext

import (
 "go/ast"

 "golang.org/x/tools/go/analysis"
)

var Analyzer = &analysis.Analyzer{
 Name: "firstparamcontext",
 Doc:  "Checks that functions first param type is Context",
 Run:  run,
}

func run(pass *analysis.Pass) (interface{}, error) {
 inspect := func(node ast.Node) bool {
  funcDecl, ok := node.(*ast.FuncDecl)
  if !ok {
   return true
  }

  params := funcDecl.Type.Params.List // get params
  // list is equal of zero that don't need to checker.
  if len(params) == 0 {
   return true
  }

  firstParamType, ok := params[0].Type.(*ast.SelectorExpr)
  if ok && firstParamType.Sel.Name == "Context" {
   return true
  }

  pass.Reportf(node.Pos(), "''%s' function first params should be Context\n",
   funcDecl.Name.Name)
  return true
 }

 for _, f := range pass.Files {
  ast.Inspect(f, inspect)
 }
 return nil, nil
}

然后添加分析器:

package main

import (
 "asong.cloud/Golang_Dream/code_demo/custom_linter/firstparamcontext"
 "golang.org/x/tools/go/analysis/singlechecker"
)

func main() {
 singlechecker.Main(firstparamcontext.Analyzer)
}

命令行执行如下:

$ go run ./main.go -- ./example.go 
/Users/go/src/asong.cloud/Golang_Dream/code_demo/custom_linter/testfirstparamcontext/example.go:3:1: ''add' function first params should be Context

如果我们想添加更多的规则,使用golang.org/x/tools/go/analysis/multichecker追加即可。

集成到golang-cli

我们可以把golang-cli的代码下载到本地,然后在pkg/golinters 下添加firstparamcontext.go,代码如下:

import (
 "golang.org/x/tools/go/analysis"

 "github.com/golangci/golangci-lint/pkg/golinters/goanalysis"

 "github.com/fisrtparamcontext"
)


func NewfirstparamcontextCheck() *goanalysis.Linter {
 return goanalysis.NewLinter(
  "firstparamcontext",
  "Checks that functions first param type is Context",
  []*analysis.Analyzer{firstparamcontext.Analyzer},
  nil,
 ).WithLoadMode(goanalysis.LoadModeSyntax)
}

然后重新make一个golang-cli可执行文件,加到我们的项目中就可以了;

总结

golang-cli仓库中pkg/golinters目录下存放了很多静态检查代码,学会一个知识点的最快办法就是抄代码,先学会怎么使用的,慢慢再把它变成我们自己的;本文没有对AST标准库做过多的介绍,因为这部分文字描述比较难以理解,最好的办法还是自己去看官方文档、加上实践才能更快的理解。

本文所有代码已经上传:https://github.com/asong2020/Golang_Dream/tree/master/code_demo/custom_linter


The above is the detailed content of How to customize linter (static checking tool) in Go language. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:Golang菜鸟. If there is any infringement, please contact admin@php.cn delete
The Performance Race: Golang vs. CThe Performance Race: Golang vs. CApr 16, 2025 am 12:07 AM

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

Golang vs. C  : Code Examples and Performance AnalysisGolang vs. C : Code Examples and Performance AnalysisApr 15, 2025 am 12:03 AM

Golang is suitable for rapid development and concurrent programming, while C is more suitable for projects that require extreme performance and underlying control. 1) Golang's concurrency model simplifies concurrency programming through goroutine and channel. 2) C's template programming provides generic code and performance optimization. 3) Golang's garbage collection is convenient but may affect performance. C's memory management is complex but the control is fine.

Golang's Impact: Speed, Efficiency, and SimplicityGolang's Impact: Speed, Efficiency, and SimplicityApr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

C   and Golang: When Performance is CrucialC and Golang: When Performance is CrucialApr 13, 2025 am 12:11 AM

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang in Action: Real-World Examples and ApplicationsGolang in Action: Real-World Examples and ApplicationsApr 12, 2025 am 12:11 AM

Golang excels in practical applications and is known for its simplicity, efficiency and concurrency. 1) Concurrent programming is implemented through Goroutines and Channels, 2) Flexible code is written using interfaces and polymorphisms, 3) Simplify network programming with net/http packages, 4) Build efficient concurrent crawlers, 5) Debugging and optimizing through tools and best practices.

Golang: The Go Programming Language ExplainedGolang: The Go Programming Language ExplainedApr 10, 2025 am 11:18 AM

The core features of Go include garbage collection, static linking and concurrency support. 1. The concurrency model of Go language realizes efficient concurrent programming through goroutine and channel. 2. Interfaces and polymorphisms are implemented through interface methods, so that different types can be processed in a unified manner. 3. The basic usage demonstrates the efficiency of function definition and call. 4. In advanced usage, slices provide powerful functions of dynamic resizing. 5. Common errors such as race conditions can be detected and resolved through getest-race. 6. Performance optimization Reuse objects through sync.Pool to reduce garbage collection pressure.

Golang's Purpose: Building Efficient and Scalable SystemsGolang's Purpose: Building Efficient and Scalable SystemsApr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Apr 02, 2025 pm 05:24 PM

Confused about the sorting of SQL query results. In the process of learning SQL, you often encounter some confusing problems. Recently, the author is reading "MICK-SQL Basics"...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!