# Go standards and style guidelines
> 原文:[https://docs.gitlab.com/ee/development/go_guide/](https://docs.gitlab.com/ee/development/go_guide/)
* [Overview](#overview)
* [Dependency Management](#dependency-management)
* [Code Review](#code-review)
* [Security](#security)
* [Finding a reviewer](#finding-a-reviewer)
* [Code style and format](#code-style-and-format)
* [Automatic linting](#automatic-linting)
* [Dependencies](#dependencies)
* [Modules](#modules)
* [ORM](#orm)
* [Migrations](#migrations)
* [Testing](#testing)
* [Testing frameworks](#testing-frameworks)
* [Subtests](#subtests)
* [Better output in tests](#better-output-in-tests)
* [Table-Driven Tests](#table-driven-tests)
* [Defining test cases](#defining-test-cases)
* [Contents of the test case](#contents-of-the-test-case)
* [Variable names](#variable-names)
* [Benchmarks](#benchmarks)
* [Error handling](#error-handling)
* [Adding context](#adding-context)
* [Naming](#naming)
* [Checking Error types](#checking-error-types)
* [References for working with errors](#references-for-working-with-errors)
* [CLIs](#clis)
* [Daemons](#daemons)
* [Logging](#logging)
* [Structured (JSON) logging](#structured-json-logging)
* [How to use Logrus](#how-to-use-logrus)
* [Tracing and Correlation](#tracing-and-correlation)
* [Context](#context)
* [Dockerfiles](#dockerfiles)
* [Distributing Go binaries](#distributing-go-binaries)
* [Updating Go version](#updating-go-version)
* [Supporting multiple Go versions](#supporting-multiple-go-versions)
* [Secure Team standards and style guidelines](#secure-team-standards-and-style-guidelines)
* [Code style and format](#code-style-and-format-1)
# Go standards and style guidelines[](#go-standards-and-style-guidelines "Permalink")
本文档介绍了使用[Go 语言的](https://s0golang0org.icopy.site) GitLab 项目的各种指南和最佳实践.
## Overview[](#overview "Permalink")
GitLab 构建在[Ruby on Rails](https://rubyonrails.org/)之上,但我们还在有意义的项目中使用 Go. Go 是一种非常强大的语言,具有许多优点,最适合具有大量 IO(磁盘/网络访问),HTTP 请求,并行处理等的项目.由于我们在 git 上都有 Ruby on Rails 和 Go,因此我们应该仔细评估两者中哪一个最适合工作.
该页面旨在根据我们的各种经验来定义和组织我们的 Go 准则. 几个项目是从不同的标准开始的,但仍然可以有一些具体说明. 它们将在各自的`README.md`或`PROCESS.md`文件中进行描述.
## Dependency Management[](#dependency-management "Permalink")
Go 使用基于源的策略进行依赖性管理. 依赖项从其源存储库中下载为源. 这不同于更常见的基于工件的策略,在后者中,依赖项是从与依赖项源存储库分开的程序包存储库中作为工件下载的.
Go 在 1.11 之前没有对版本管理的一流支持. 该版本引入了 Go 模块和语义版本控制的使用. Go 1.12 引入了模块代理,它们可以用作客户端和源版本控制系统之间的中介,以及校验和数据库,可以用于验证依赖项下载的完整性.
有关更多详细信息,请参见[Go 中的依赖管理](dependencies.html) .
## Code Review[](#code-review "Permalink")
我们遵循[Go Code Review Comments](https://github.com/golang/go/wiki/CodeReviewComments)的通用原则.
审阅者和维护者应注意:
* `defer`功能:在需要时以及在`err`检查之后确保存在.
* 注入依赖项作为参数.
* 封送至 JSON 时,其 Void 结构(生成`null`而不是`[]` ).
### Security[](#security "Permalink")
安全是我们在 GitLab 的首要任务. 在代码审查期间,我们必须注意代码中可能存在的安全漏洞:
* 使用文字/模板时的 XSS
* 使用大猩猩的 CSRF 保护
* 使用没有已知漏洞的 Go 版本
* 不要泄漏秘密令牌
* SQL 注入
记住要运行[SAST](../../user/application_security/sast/index.html)和[依赖项扫描](../../user/application_security/dependency_scanning/index.html) 在您的项目(或至少是[gosec 分析器](https://gitlab.com/gitlab-org/security-products/analyzers/gosec) )上,并遵守我们的[安全要求](../code_review.html#security-requirements) .
Web 服务器可以利用[Secure](https://github.com/unrolled/secure)等中间件的优势.
### Finding a reviewer[](#finding-a-reviewer "Permalink")
我们的许多项目规模太小,无法拥有专职维护人员. 这就是为什么我们在 GitLab 有一个共享的 Go 评论者池. 要查找审阅者,请使用手册"工程项目"页面上" GitLab"项目的["执行"部分](https://about.gitlab.com/handbook/engineering/projects/#gitlab_reviewers_go) .
要将您自己添加到此列表中,请将以下内容添加到[team.yml](https://gitlab.com/gitlab-com/www-gitlab-com/blob/master/data/team.yml)文件中的个人资料中,并请您的经理进行审核和合并.
```
projects:
gitlab: reviewer go
```
## Code style and format[](#code-style-and-format "Permalink")
* 避免全局变量,即使在软件包中也是如此. 这样,如果多次包含该软件包,您将产生副作用.
* 在提交之前使用`goimports` . [goimports](https://s0godoc0org.icopy.site/golang.org/x/tools/cmd/goimports)是一个工具,除了格式化导入行,添加缺少的行和删除未引用的行之外, [它还可以](https://s0golang0org.icopy.site/cmd/gofmt/)使用[Gofmt](https://s0golang0org.icopy.site/cmd/gofmt/)自动格式化 Go 源代码.
大多数编辑器/ IDE 允许您在保存文件之前/之后运行命令,您可以将其设置为运行`goimports`以便在保存时将其应用于每个文件.
* 将私有方法放在源文件中第一个调用方方法的下面.
### Automatic linting[](#automatic-linting "Permalink")
所有 Go 项目均应包括以下 GitLab CI / CD 作业:
```
lint:
image: registry.gitlab.com/gitlab-org/gitlab-build-images:golangci-lint-alpine
stage: test
script:
# Use default .golangci.yml file from the image if one is not present in the project root.
- '[ -e .golangci.yml ] || cp /golangci/.golangci.yml .'
# Write the code coverage report to gl-code-quality-report.json
# and print linting issues to stdout in the format: path/to/file:line description
- golangci-lint run --out-format code-climate | tee gl-code-quality-report.json | jq -r '.[] | "\(.location.path):\(.location.lines.begin) \(.description)"'
artifacts:
reports:
codequality: gl-code-quality-report.json
paths:
- gl-code-quality-report.json
allow_failure: true
```
在项目的根目录中包含`.golangci.yml`可以配置`golangci-lint` . 此[示例](https://github.com/golangci/golangci-lint/blob/master/.golangci.example.yml)中列出了`golangci-lint`所有选项.
[递归包含](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/56836)可用后,您就可以共享作业模板,例如此[分析器](https://gitlab.com/gitlab-org/security-products/ci-templates/raw/master/includes-dev/analyzer.yml) .
## Dependencies[](#dependencies "Permalink")
依赖性应保持最小. 根据我们的[批准指南](../code_review.html#approval-guidelines) ,应在合并请求中对引入新的依赖项进行争论. 两种[许可证管理](../../user/compliance/license_compliance/index.html) 和[依赖项扫描](../../user/application_security/dependency_scanning/index.html) 应该在所有项目上激活,以确保新的依赖项安全状态和许可证兼容性.
### Modules[](#modules "Permalink")
从 Go 1.11 开始,名称[Go 的模块](https://github.com/golang/go/wiki/Modules)后面提供了一个标准的依赖系统. 它提供了一种方法来定义和锁定可复制构建的依赖关系. 应尽可能使用它.
当使用 Go Modules 时,不应有`vendor/`目录. 相反,Go 会在需要构建项目时自动下载依赖项. 这与 Ruby 项目中 Bundler 处理依赖关系的方式一致,并使合并请求更易于查看.
在某些情况下,例如构建一个 Go 项目以充当另一个项目的 CI 运行的依赖项,删除`vendor/`目录意味着必须重复下载代码,这可能由于速率限制或网络而导致间歇性问题.失败. 在这种情况下,您应该[在之间缓存下载的代码](../../ci/caching/index.html#caching-go-dependencies) .
Go <v1.11.4 中的[模块校验和](https://github.com/golang/go/issues/29278)存在一个[错误](https://github.com/golang/go/issues/29278) ,因此请确保至少使用此版本,以避免`checksum mismatch`错误.
### ORM[](#orm "Permalink")
我们不在 GitLab 上使用对象关系映射库(ORM)(Ruby on Rails 中的[ActiveRecord](https://guides.rubyonrails.org/active_record_basics.html)除外). 可以使用服务来结构化项目以避免它们. [PQ](https://github.com/lib/pq)应该足以与 PostgreSQL 数据库进行交互.
### Migrations[](#migrations "Permalink")
在极少数情况下,如果管理托管数据库,则必须使用 ActiveRecord 提供的迁移系统. 像[Journey](https://github.com/db-journey/journey)这样的简单库,可以在`postgres`容器中使用,可以部署为长期运行的 pod. 新版本将部署新的 Pod,并自动迁移数据.
## Testing[](#testing "Permalink")
### Testing frameworks[](#testing-frameworks "Permalink")
我们不应该使用任何特定的库或框架来进行测试,因为[标准库](https://s0golang0org.icopy.site/pkg/)已经提供了入门所需的一切. 如果需要更复杂的测试工具,则在我们决定使用特定的库或框架时,以下外部依赖项可能值得考虑:
* [Testify](https://github.com/stretchr/testify)
* [httpexpect](https://github.com/gavv/httpexpect)
### Subtests[](#subtests "Permalink")
尽可能使用[子测试,](https://blog.golang.org/subtests)以提高代码的可读性和测试输出.
### Better output in tests[](#better-output-in-tests "Permalink")
When comparing expected and actual values in tests, use [`testify/require.Equal`](https://s0godoc0org.icopy.site/github.com/stretchr/testify/require), [`testify/require.EqualError`](https://s0godoc0org.icopy.site/github.com/stretchr/testify/require), [`testify/require.EqualValues`](https://s0godoc0org.icopy.site/github.com/stretchr/testify/require), and others to improve readability when comparing structs, errors, large portions of text, or JSON documents:
```
type TestData struct {
// ...
}
func FuncUnderTest() TestData {
// ...
}
func Test(t *testing.T) {
t.Run("FuncUnderTest", func(t *testing.T) {
want := TestData{}
got := FuncUnderTest()
require.Equal(t, want, got) // note that expected value comes first, then comes the actual one ("diff" semantics)
})
}
```
### Table-Driven Tests[](#table-driven-tests "Permalink")
当您为同一功能输入/输出有多个条目时,使用[表驱动测试](https://github.com/golang/go/wiki/TableDrivenTests)通常是一个好习惯. 以下是编写表驱动测试时可以遵循的一些准则. 这些准则主要是从 Go 标准库源代码中提取的. 请记住,在合理的时候不要遵循这些准则.
#### Defining test cases[](#defining-test-cases "Permalink")
每个表条目都是一个完整的测试用例,其中包含输入和预期结果,有时还包含其他信息(例如测试名称),以使测试输出易于阅读.
* 在测试内部[定义一片匿名结构](https://github.com/golang/go/blob/50bd1c4d4eb4fac8ddeb5f063c099daccfb71b26/src/encoding/csv/reader_test.go#L16) .
* 在测试之外[定义一片匿名结构](https://github.com/golang/go/blob/55d31e16c12c38d36811bdee65ac1f7772148250/src/cmd/go/internal/module/module_test.go#L9-L66) .
* 用于代码重用的[命名结构](https://github.com/golang/go/blob/2e0cd2aef5924e48e1ceb74e3d52e76c56dd34cc/src/cmd/go/internal/modfetch/coderepo_test.go#L54-L69) .
* [Using `map[string]struct{}`](https://github.com/golang/go/blob/6d5caf38e37bf9aeba3291f1f0b0081f934b1187/src/cmd/trace/annotations_test.go#L180-L235).
#### Contents of the test case[](#contents-of-the-test-case "Permalink")
* 理想情况下,每个测试用例都应具有一个带有唯一标识符的字段,以用于命名子测试. 在 Go 标准库中,这通常是`name string`字段.
* 当您在测试用例中指定将用于断言的内容时,请使用`want` / `expect` / `actual` .
#### Variable names[](#variable-names "Permalink")
* 每个表驱动的测试映射/结构片段都可以命名为`tests` .
* 遍历`tests` ,匿名结构可以称为`tt`或`tc` .
* 测试的描述可以称为`name` / `testName` / `tn` .
### Benchmarks[](#benchmarks "Permalink")
处理大量 IO 或复杂操作的程序应始终包含[基准测试](https://s0golang0org.icopy.site/pkg/testing/) ,以确保随时间推移的性能一致性.
## Error handling[](#error-handling "Permalink")
### Adding context[](#adding-context "Permalink")
在返回错误之前添加上下文可能会有所帮助,而不仅仅是返回错误. 这使开发人员可以了解程序进入错误状态时试图做什么,从而使调试更加容易.
例如:
```
// Wrap the error
return nil, fmt.Errorf("get cache %s: %w", f.Name, err)
// Just add context
return nil, fmt.Errorf("saving cache %s: %v", f.Name, err)
```
A few things to keep in mind when adding context:
* 确定是否要向调用者公开潜在的错误. 如果是这样,请使用`%w` ,否则请使用`%v` .
* 不要使用`failed` , `error` , `didn't` . 因为这是一个错误,所以用户已经知道某件事失败了,这可能导致出现诸如`failed xx failed xx failed xx`类的字符串. 解释*什么* ,而不是失败.
* 错误字符串不应大写或以标点符号或换行符结尾. 您可以使用`golint`进行检查.
### Naming[](#naming "Permalink")
* 使用哨兵错误时,应始终将它们命名为`ErrXxx` .
* 创建新的错误类型时,应始终将其命名为`XxxError` .
### Checking Error types[](#checking-error-types "Permalink")
* 要检查错误是否相等,请不要使用`==` . 使用[`errors.Is`](https://pkg.go.dev/errors?tab=doc#Is)代替(对于围棋版本> = 1.13).
* 要检查错误是否属于某种类型,请不要使用类型断言,而应使用[`errors.As`](https://pkg.go.dev/errors?tab=doc#As) (对于 Go 版本> = 1.13).
### References for working with errors[](#references-for-working-with-errors "Permalink")
* [Go 1.13 errors](https://blog.golang.org/go1.13-errors).
* [Programing with errors](https://peter.bourgon.org/blog/2019/09/11/programming-with-errors.html).
* [Don’t just check errors, handle them gracefully](https://dave.cheney.net/2016/04/27/dont-just-check-errors-handle-them-gracefully).
## CLIs[](#clis "Permalink")
每个 Go 程序都是从命令行启动的. [cli](https://github.com/urfave/cli)是用于创建命令行应用程序的便捷软件包. 无论项目是守护程序还是简单的 cli 工具,都应使用它. 可以将标志直接映射到[环境变量](https://github.com/urfave/cli#values-from-the-environment) ,这些[变量](https://github.com/urfave/cli#values-from-the-environment)同时记录和集中与程序的所有可能的命令行交互. 不要使用`os.GetEnv` ,它会将变量隐藏在代码深处.
## Daemons[](#daemons "Permalink")
### Logging[](#logging "Permalink")
强烈建议为守护程序使用日志记录库. 即使标准库中有一个`log`包,我们通常也使用[Logrus](https://github.com/sirupsen/logrus) . 它的插件("挂钩")系统使其成为功能强大的日志记录库,并能够直接在记录器级别添加通知程序和格式化程序.
#### Structured (JSON) logging[](#structured-json-logging "Permalink")
理想情况下,每个二进制文件都必须具有结构化(JSON)日志记录,因为它有助于搜索和过滤日志. 在 GitLab,我们使用 JSON 格式的结构化日志记录,因为我们所有的基础架构都假定这样做. 使用[Logrus 时](https://github.com/sirupsen/logrus) ,只需使用[JSON 格式化程序中](https://github.com/sirupsen/logrus#formatters)的构建即可打开结构化日志记录. 这遵循我们在[Ruby 应用程序中](../logging.html#use-structured-json-logging)使用的相同日志记录类型.
#### How to use Logrus[](#how-to-use-logrus "Permalink")
使用[Logrus](https://github.com/sirupsen/logrus)软件包时,应遵循一些准则:
* 打印错误时,请使用[WithError](https://s0godoc0org.icopy.site/github.com/sirupsen/logrus) . 例如, `logrus.WithError(err).Error("Failed to do something")` .
* 由于我们使用[结构化日志记录](#structured-json-logging) ,因此可以在该代码路径的上下文中记录字段,例如使用[`WithField`](https://s0godoc0org.icopy.site/github.com/sirupsen/logrus)或[`WithFields`](https://s0godoc0org.icopy.site/github.com/sirupsen/logrus)的请求的 URI. 例如, `logrus.WithField("file", "/app/go").Info("Opening dir")` . 如果必须记录多个键,请始终使用`WithFields`而不是多次调用`WithField` .
### Tracing and Correlation[](#tracing-and-correlation "Permalink")
[LabKit](https://gitlab.com/gitlab-org/labkit)是为 Go 服务保留通用库的地方. 目前,它已销售到两个项目:Workhorse 和 Gitaly,并且导出了两个主要(但相关)功能:
* [`gitlab.com/gitlab-org/labkit/correlation`](https://gitlab.com/gitlab-org/labkit/tree/master/correlation) :用于传播和提取服务之间的相关 ID.
* [`gitlab.com/gitlab-org/labkit/tracing`](https://gitlab.com/gitlab-org/labkit/tree/master/tracing): for instrumenting Go libraries for distributed tracing.
这为我们提供了对底层实现的精简抽象,该抽象实现在 Workhorse,Gitaly 以及将来的其他 Go 服务器之间保持一致. 例如,对于`gitlab.com/gitlab-org/labkit/tracing`我们可以从直接使用`gitlab.com/gitlab-org/labkit/tracing`切换为使用 Zipkin 或 Gokit 自己的跟踪包装器,而无需更改应用程序代码,同时仍保持相同的一致配置机制(即`GITLAB_TRACING`环境变量).
### Context[](#context "Permalink")
由于守护程序是长期运行的应用程序,因此它们应具有管理取消的机制,并避免不必要的资源消耗(这可能导致 DDOS 漏洞). [Go Context](https://github.com/golang/go/wiki/CodeReviewComments#contexts)应该在可以阻塞并作为第一个参数传递的函数中使用.
## Dockerfiles[](#dockerfiles "Permalink")
每个项目都应在其存储库的根目录中具有一个`Dockerfile` ,以构建和运行该项目. 由于 Go 程序是静态二进制文件,因此它们不需要任何外部依赖关系,并且最终映像中的 shell 无用. 我们鼓励进行[多阶段构建](https://s0docs0docker0com.icopy.site/develop/develop-images/multistage-build/) :
* 他们使用户可以使用正确的 Go 版本和依赖项来构建项目.
* 它们生成一个小的,自包含的图像,该图像取自`Scratch` .
生成的 Docker 映像应在其`Entrypoint`处具有程序以创建可移植命令. 这样,任何人都可以运行该映像,并且没有参数就可以显示其帮助消息(如果已使用`cli` ).
## Distributing Go binaries[](#distributing-go-binaries "Permalink")
除了发布自己的二进制文件的[GitLab Runner](https://gitlab.com/gitlab-org/gitlab-runner)之外,我们的 Go 二进制文件都是由" [分发"组](https://about.gitlab.com/handbook/product/product-categories/#distribution-group)管理的项目创建的.
[Omnibus GitLab](https://gitlab.com/gitlab-org/omnibus-gitlab)项目创建一个包含所有二进制文件的单一的操作系统软件包,而[Cloud-Native GitLab(CNG)](https://gitlab.com/gitlab-org/build/CNG)项目发布一组 Docker 映像和 Helm 图表以将它们粘合在一起.
两种方法对所有项目都使用相同版本的 Go,因此确保我们所有使用 Go 的项目在其测试矩阵中至少具有一个相同的 Go 版本非常重要. 您可以检查[Omnibus](https://gitlab.com/gitlab-org/gitlab-omnibus-builder/blob/master/docker/Dockerfile_debian_10#L59)当前正在使用的 Go 版本以及[CNG](https://gitlab.com/gitlab-org/build/cng/blob/master/ci_files/variables.yml#L12)正在使用的版本.
### Updating Go version[](#updating-go-version "Permalink")
我们应该始终使用[受支持](https://s0golang0org.icopy.site/doc/devel/release.html)的 Go [版本](https://s0golang0org.icopy.site/doc/devel/release.html) ,即三个最新的次要版本之一,并且应该始终使用该版本的最新补丁程序级别,因为它可能包含安全修复程序.
更改版本会影响正在编译的每个项目,因此在更改程序包构建器以使用它之前,请确保已更新所有项目以针对新的 Go 版本进行测试非常重要. 尽管[Go 保证了兼容性](https://s0golang0org.icopy.site/doc/go1compat) ,但次要版本之间的更改可能会暴露错误或在我们的项目中引起问题.
选择要使用的新 Go 版本之后,更新 Omnibus 和 CNG 的步骤如下:
* [创建于 CNG 项目的合并请求](https://gitlab.com/gitlab-org/build/CNG/edit/master/ci_files/variables.yml?branch_name=update-go-version) ,更新`GO_VERSION`在`ci_files/variables.yml` .
* 在[`gitlab-omnibus-builder`项目中](https://gitlab.com/gitlab-org/gitlab-omnibus-builder)创建合并请求,更新`GO_VERSION` `docker/`目录中的每个文件,以便`GO_VERSION`设置`GO_VERSION` . [这是一个例子](https://gitlab.com/gitlab-org/gitlab-omnibus-builder/-/merge_requests/125/diffs) .
* 标记包含更改的`gitlab-omnibus-builder`的新版本.
* [在`omnibus-gitlab`项目中创建合并请求](https://gitlab.com/gitlab-org/omnibus-gitlab/edit/master/.gitlab-ci.yml?branch_name=update-gitlab-omnibus-builder-version) ,更新`BUILDER_IMAGE_REVISION`以匹配新创建的标记.
为了减少两种分发方法之间不必要的差异,Omnibus 和 CNG **应该始终使用相同的 Go 版本** .
### Supporting multiple Go versions[](#supporting-multiple-go-versions "Permalink")
出于以下原因,各个 Golang 项目需要支持多个 Go 版本:
1. 当新的 Go 版本发布时,我们应该开始将其集成到 CI 管道中,以验证与新编译器的兼容性.
2. 我们必须支持[Omnibus 官方的 Go 版本](#updating-go-version) ,该[版本](#updating-go-version)可能在最新的次要版本之后.
3. 当 Omnibus 切换为 Go 版本时,我们仍可能需要支持旧版本进行安全反向移植.
保持对 Go 的 3 个最新次要版本的支持,可以轻松满足这 3 个要求.
可以放弃对最旧的 Go 版本的支持,并且仅支持 2 个最新版本,如果这足以支持向后 3 个 GitLab 次要版本的反向移植.
Example:
如果我们要丢弃的支持`go 1.11`在 GitLab `12.10` ,我们需要验证我们使用哪去版本`12.9` , `12.8`和`12.7` .
我们将不考虑活动的里程碑`12.10` ,因为在关键安全发布的情况下将需要`12.7`的反向端口.
1. 如果从 GitLab `12.7`开始[Omnibus 和 CNG](#updating-go-version)都在使用 Go `1.12` ,那么我们可以放心地放弃对`1.11`支持.
2. 如果 Omnibus 或 CNG 在 GitLab `12.7`中使用`1.11` ,那么我们仍然需要保持对 Go `1.11`支持,以便更轻松地向后移植安全修复程序.
## Secure Team standards and style guidelines[](#secure-team-standards-and-style-guidelines "Permalink")
以下是一些特定于安全团队的样式准则.
### Code style and format[](#code-style-and-format-1 "Permalink")
在提交之前,请使用`goimports -local gitlab.com/gitlab-org` . [goimports](https://s0godoc0org.icopy.site/golang.org/x/tools/cmd/goimports)是一个工具,除了格式化导入行,添加缺少的行和删除未引用的行之外, [它还可以](https://s0golang0org.icopy.site/cmd/gofmt/)使用[Gofmt](https://s0golang0org.icopy.site/cmd/gofmt/)自动格式化 Go 源代码. 通过使用`-local gitlab.com/gitlab-org`选项, `goimports`会将本地引用的软件包与外部软件包分开分组. 有关更多详细信息,请参见 Go Wiki 上"代码审查注释"页面[的导入部分](https://github.com/golang/go/wiki/CodeReviewComments#imports) . 大多数编辑器/ IDE 允许您在保存文件之前/之后运行命令,您可以将其设置为运行`goimports -local gitlab.com/gitlab-org`以便在保存时将其应用于每个文件.
* * *
[Return to Development documentation](../README.html).
- GitLab Docs
- Installation
- Requirements
- GitLab cloud native Helm Chart
- Install GitLab with Docker
- Installation from source
- Install GitLab on Microsoft Azure
- Installing GitLab on Google Cloud Platform
- Installing GitLab on Amazon Web Services (AWS)
- Analytics
- Code Review Analytics
- Productivity Analytics
- Value Stream Analytics
- Kubernetes clusters
- Adding and removing Kubernetes clusters
- Adding EKS clusters
- Adding GKE clusters
- Group-level Kubernetes clusters
- Instance-level Kubernetes clusters
- Canary Deployments
- Cluster Environments
- Deploy Boards
- GitLab Managed Apps
- Crossplane configuration
- Cluster management project (alpha)
- Kubernetes Logs
- Runbooks
- Serverless
- Deploying AWS Lambda function using GitLab CI/CD
- Securing your deployed applications
- Groups
- Contribution Analytics
- Custom group-level project templates
- Epics
- Manage epics
- Group Import/Export
- Insights
- Issues Analytics
- Iterations
- Public access
- SAML SSO for GitLab.com groups
- SCIM provisioning using SAML SSO for GitLab.com groups
- Subgroups
- Roadmap
- Projects
- GitLab Secure
- Security Configuration
- Container Scanning
- Dependency Scanning
- Dependency List
- Static Application Security Testing (SAST)
- Secret Detection
- Dynamic Application Security Testing (DAST)
- GitLab Security Dashboard
- Offline environments
- Standalone Vulnerability pages
- Security scanner integration
- Badges
- Bulk editing issues and merge requests at the project level
- Code Owners
- Compliance
- License Compliance
- Compliance Dashboard
- Create a project
- Description templates
- Deploy Keys
- Deploy Tokens
- File finder
- Project integrations
- Integrations
- Atlassian Bamboo CI Service
- Bugzilla Service
- Custom Issue Tracker service
- Discord Notifications service
- Enabling emails on push
- GitHub project integration
- Hangouts Chat service
- Atlassian HipChat
- Irker IRC Gateway
- GitLab Jira integration
- Mattermost Notifications Service
- Mattermost slash commands
- Microsoft Teams service
- Mock CI Service
- Prometheus integration
- Redmine Service
- Slack Notifications Service
- Slack slash commands
- GitLab Slack application
- Webhooks
- YouTrack Service
- Insights
- Issues
- Crosslinking Issues
- Design Management
- Confidential issues
- Due dates
- Issue Boards
- Issue Data and Actions
- Labels
- Managing issues
- Milestones
- Multiple Assignees for Issues
- Related issues
- Service Desk
- Sorting and ordering issue lists
- Issue weight
- Associate a Zoom meeting with an issue
- Merge requests
- Allow collaboration on merge requests across forks
- Merge Request Approvals
- Browser Performance Testing
- How to create a merge request
- Cherry-pick changes
- Code Quality
- Load Performance Testing
- Merge Request dependencies
- Fast-forward merge requests
- Merge when pipeline succeeds
- Merge request conflict resolution
- Reverting changes
- Reviewing and managing merge requests
- Squash and merge
- Merge requests versions
- Draft merge requests
- Members of a project
- Migrating projects to a GitLab instance
- Import your project from Bitbucket Cloud to GitLab
- Import your project from Bitbucket Server to GitLab
- Migrating from ClearCase
- Migrating from CVS
- Import your project from FogBugz to GitLab
- Gemnasium
- Import your project from GitHub to GitLab
- Project importing from GitLab.com to your private GitLab instance
- Import your project from Gitea to GitLab
- Import your Jira project issues to GitLab
- Migrating from Perforce Helix
- Import Phabricator tasks into a GitLab project
- Import multiple repositories by uploading a manifest file
- Import project from repo by URL
- Migrating from SVN to GitLab
- Migrating from TFVC to Git
- Push Options
- Releases
- Repository
- Branches
- Git Attributes
- File Locking
- Git file blame
- Git file history
- Repository mirroring
- Protected branches
- Protected tags
- Push Rules
- Reduce repository size
- Signing commits with GPG
- Syntax Highlighting
- GitLab Web Editor
- Web IDE
- Requirements Management
- Project settings
- Project import/export
- Project access tokens (Alpha)
- Share Projects with other Groups
- Snippets
- Static Site Editor
- Wiki
- Project operations
- Monitor metrics for your CI/CD environment
- Set up alerts for Prometheus metrics
- Embedding metric charts within GitLab-flavored Markdown
- Embedding Grafana charts
- Using the Metrics Dashboard
- Dashboard YAML properties
- Metrics dashboard settings
- Panel types for dashboards
- Using Variables
- Templating variables for metrics dashboards
- Prometheus Metrics library
- Monitoring AWS Resources
- Monitoring HAProxy
- Monitoring Kubernetes
- Monitoring NGINX
- Monitoring NGINX Ingress Controller
- Monitoring NGINX Ingress Controller with VTS metrics
- Alert Management
- Error Tracking
- Tracing
- Incident Management
- GitLab Status Page
- Feature Flags
- GitLab CI/CD
- GitLab CI/CD pipeline configuration reference
- GitLab CI/CD include examples
- Introduction to CI/CD with GitLab
- Getting started with GitLab CI/CD
- How to enable or disable GitLab CI/CD
- Using SSH keys with GitLab CI/CD
- Migrating from CircleCI
- Migrating from Jenkins
- Auto DevOps
- Getting started with Auto DevOps
- Requirements for Auto DevOps
- Customizing Auto DevOps
- Stages of Auto DevOps
- Upgrading PostgreSQL for Auto DevOps
- Cache dependencies in GitLab CI/CD
- GitLab ChatOps
- Cloud deployment
- Docker integration
- Building Docker images with GitLab CI/CD
- Using Docker images
- Building images with kaniko and GitLab CI/CD
- GitLab CI/CD environment variables
- Predefined environment variables reference
- Where variables can be used
- Deprecated GitLab CI/CD variables
- Environments and deployments
- Protected Environments
- GitLab CI/CD Examples
- Test a Clojure application with GitLab CI/CD
- Using Dpl as deployment tool
- Testing a Phoenix application with GitLab CI/CD
- End-to-end testing with GitLab CI/CD and WebdriverIO
- DevOps and Game Dev with GitLab CI/CD
- Deploy a Spring Boot application to Cloud Foundry with GitLab CI/CD
- How to deploy Maven projects to Artifactory with GitLab CI/CD
- Testing PHP projects
- Running Composer and NPM scripts with deployment via SCP in GitLab CI/CD
- Test and deploy Laravel applications with GitLab CI/CD and Envoy
- Test and deploy a Python application with GitLab CI/CD
- Test and deploy a Ruby application with GitLab CI/CD
- Test and deploy a Scala application to Heroku
- GitLab CI/CD for external repositories
- Using GitLab CI/CD with a Bitbucket Cloud repository
- Using GitLab CI/CD with a GitHub repository
- GitLab Pages
- GitLab Pages
- GitLab Pages domain names, URLs, and baseurls
- Create a GitLab Pages website from scratch
- Custom domains and SSL/TLS Certificates
- GitLab Pages integration with Let's Encrypt
- GitLab Pages Access Control
- Exploring GitLab Pages
- Incremental Rollouts with GitLab CI/CD
- Interactive Web Terminals
- Optimizing GitLab for large repositories
- Metrics Reports
- CI/CD pipelines
- Pipeline Architecture
- Directed Acyclic Graph
- Multi-project pipelines
- Parent-child pipelines
- Pipelines for Merge Requests
- Pipelines for Merged Results
- Merge Trains
- Job artifacts
- Pipeline schedules
- Pipeline settings
- Triggering pipelines through the API
- Review Apps
- Configuring GitLab Runners
- GitLab CI services examples
- Using MySQL
- Using PostgreSQL
- Using Redis
- Troubleshooting CI/CD
- GitLab Package Registry
- GitLab Container Registry
- Dependency Proxy
- GitLab Composer Repository
- GitLab Conan Repository
- GitLab Maven Repository
- GitLab NPM Registry
- GitLab NuGet Repository
- GitLab PyPi Repository
- API Docs
- API resources
- .gitignore API
- GitLab CI YMLs API
- Group and project access requests API
- Appearance API
- Applications API
- Audit Events API
- Avatar API
- Award Emoji API
- Project badges API
- Group badges API
- Branches API
- Broadcast Messages API
- Project clusters API
- Group clusters API
- Instance clusters API
- Commits API
- Container Registry API
- Custom Attributes API
- Dashboard annotations API
- Dependencies API
- Deploy Keys API
- Deployments API
- Discussions API
- Dockerfiles API
- Environments API
- Epics API
- Events
- Feature Flags API
- Feature flag user lists API
- Freeze Periods API
- Geo Nodes API
- Group Activity Analytics API
- Groups API
- Import API
- Issue Boards API
- Group Issue Boards API
- Issues API
- Epic Issues API
- Issues Statistics API
- Jobs API
- Keys API
- Labels API
- Group Labels API
- License
- Licenses API
- Issue links API
- Epic Links API
- Managed Licenses API
- Markdown API
- Group and project members API
- Merge request approvals API
- Merge requests API
- Project milestones API
- Group milestones API
- Namespaces API
- Notes API
- Notification settings API
- Packages API
- Pages domains API
- Pipeline schedules API
- Pipeline triggers API
- Pipelines API
- Project Aliases API
- Project import/export API
- Project repository storage moves API
- Project statistics API
- Project templates API
- Projects API
- Protected branches API
- Protected tags API
- Releases API
- Release links API
- Repositories API
- Repository files API
- Repository submodules API
- Resource label events API
- Resource milestone events API
- Resource weight events API
- Runners API
- SCIM API
- Search API
- Services API
- Application settings API
- Sidekiq Metrics API
- Snippets API
- Project snippets
- Application statistics API
- Suggest Changes API
- System hooks API
- Tags API
- Todos API
- Users API
- Project-level Variables API
- Group-level Variables API
- Version API
- Vulnerabilities API
- Vulnerability Findings API
- Wikis API
- GraphQL API
- Getting started with GitLab GraphQL API
- GraphQL API Resources
- API V3 to API V4
- Validate the .gitlab-ci.yml (API)
- User Docs
- Abuse reports
- User account
- Active sessions
- Deleting a User account
- Permissions
- Personal access tokens
- Profile preferences
- Threads
- GitLab and SSH keys
- GitLab integrations
- Git
- GitLab.com settings
- Infrastructure as code with Terraform and GitLab
- GitLab keyboard shortcuts
- GitLab Markdown
- AsciiDoc
- GitLab Notification Emails
- GitLab Quick Actions
- Autocomplete characters
- Reserved project and group names
- Search through GitLab
- Advanced Global Search
- Advanced Syntax Search
- Time Tracking
- GitLab To-Do List
- Administrator Docs
- Reference architectures
- Reference architecture: up to 1,000 users
- Reference architecture: up to 2,000 users
- Reference architecture: up to 3,000 users
- Reference architecture: up to 5,000 users
- Reference architecture: up to 10,000 users
- Reference architecture: up to 25,000 users
- Reference architecture: up to 50,000 users
- Troubleshooting a reference architecture set up
- Working with the bundled Consul service
- Configuring PostgreSQL for scaling
- Configuring GitLab application (Rails)
- Load Balancer for multi-node GitLab
- Configuring a Monitoring node for Scaling and High Availability
- NFS
- Working with the bundled PgBouncer service
- Configuring Redis for scaling
- Configuring Sidekiq
- Admin Area settings
- Continuous Integration and Deployment Admin settings
- Custom instance-level project templates
- Diff limits administration
- Enable and disable GitLab features deployed behind feature flags
- Geo nodes Admin Area
- GitLab Pages administration
- Health Check
- Job logs
- Labels administration
- Log system
- PlantUML & GitLab
- Repository checks
- Repository storage paths
- Repository storage types
- Account and limit settings
- Service templates
- System hooks
- Changing your time zone
- Uploads administration
- Abuse reports
- Activating and deactivating users
- Audit Events
- Blocking and unblocking users
- Broadcast Messages
- Elasticsearch integration
- Gitaly
- Gitaly Cluster
- Gitaly reference
- Monitoring GitLab
- Monitoring GitLab with Prometheus
- Performance Bar
- Usage statistics
- Object Storage
- Performing Operations in GitLab
- Cleaning up stale Redis sessions
- Fast lookup of authorized SSH keys in the database
- Filesystem Performance Benchmarking
- Moving repositories managed by GitLab
- Run multiple Sidekiq processes
- Sidekiq MemoryKiller
- Switching to Puma
- Understanding Unicorn and unicorn-worker-killer
- User lookup via OpenSSH's AuthorizedPrincipalsCommand
- GitLab Package Registry administration
- GitLab Container Registry administration
- Replication (Geo)
- Geo database replication
- Geo with external PostgreSQL instances
- Geo configuration
- Using a Geo Server
- Updating the Geo nodes
- Geo with Object storage
- Docker Registry for a secondary node
- Geo for multiple nodes
- Geo security review (Q&A)
- Location-aware Git remote URL with AWS Route53
- Tuning Geo
- Removing secondary Geo nodes
- Geo data types support
- Geo Frequently Asked Questions
- Geo Troubleshooting
- Geo validation tests
- Disaster Recovery (Geo)
- Disaster recovery for planned failover
- Bring a demoted primary node back online
- Automatic background verification
- Rake tasks
- Back up and restore GitLab
- Clean up
- Namespaces
- Maintenance Rake tasks
- Geo Rake Tasks
- GitHub import
- Import bare repositories
- Integrity check Rake task
- LDAP Rake tasks
- Listing repository directories
- Praefect Rake tasks
- Project import/export administration
- Repository storage Rake tasks
- Generate sample Prometheus data
- Uploads migrate Rake tasks
- Uploads sanitize Rake tasks
- User management
- Webhooks administration
- X.509 signatures
- Server hooks
- Static objects external storage
- Updating GitLab
- GitLab release and maintenance policy
- Security
- Password Storage
- Custom password length limits
- Restrict allowed SSH key technologies and minimum length
- Rate limits
- Webhooks and insecure internal web services
- Information exclusivity
- How to reset your root password
- How to unlock a locked user from the command line
- User File Uploads
- How we manage the TLS protocol CRIME vulnerability
- User email confirmation at sign-up
- Security of running jobs
- Proxying assets
- CI/CD Environment Variables
- Contributor and Development Docs
- Contribute to GitLab
- Community members & roles
- Implement design & UI elements
- Issues workflow
- Merge requests workflow
- Code Review Guidelines
- Style guides
- GitLab Architecture Overview
- CI/CD development documentation
- Database guides
- Database Review Guidelines
- Database Review Guidelines
- Migration Style Guide
- What requires downtime?
- Understanding EXPLAIN plans
- Rake tasks for developers
- Mass inserting Rails models
- GitLab Documentation guidelines
- Documentation Style Guide
- Documentation structure and template
- Documentation process
- Documentation site architecture
- Global navigation
- GitLab Docs monthly release process
- Telemetry Guide
- Usage Ping Guide
- Snowplow Guide
- Experiment Guide
- Feature flags in development of GitLab
- Feature flags process
- Developing with feature flags
- Feature flag controls
- Document features deployed behind feature flags
- Frontend Development Guidelines
- Accessibility & Readability
- Ajax
- Architecture
- Axios
- Design Patterns
- Frontend Development Process
- DropLab
- Emojis
- Filter
- Frontend FAQ
- GraphQL
- Icons and SVG Illustrations
- InputSetter
- Performance
- Principles
- Security
- Tooling
- Vuex
- Vue
- Geo (development)
- Geo self-service framework (alpha)
- Gitaly developers guide
- GitLab development style guides
- API style guide
- Go standards and style guidelines
- GraphQL API style guide
- Guidelines for shell commands in the GitLab codebase
- HTML style guide
- JavaScript style guide
- Migration Style Guide
- Newlines style guide
- Python Development Guidelines
- SCSS style guide
- Shell scripting standards and style guidelines
- Sidekiq debugging
- Sidekiq Style Guide
- SQL Query Guidelines
- Vue.js style guide
- Instrumenting Ruby code
- Testing standards and style guidelines
- Flaky tests
- Frontend testing standards and style guidelines
- GitLab tests in the Continuous Integration (CI) context
- Review Apps
- Smoke Tests
- Testing best practices
- Testing levels
- Testing Rails migrations at GitLab
- Testing Rake tasks
- End-to-end Testing
- Beginner's guide to writing end-to-end tests
- End-to-end testing Best Practices
- Dynamic Element Validation
- Flows in GitLab QA
- Page objects in GitLab QA
- Resource class in GitLab QA
- Style guide for writing end-to-end tests
- Testing with feature flags
- Translate GitLab to your language
- Internationalization for GitLab
- Translating GitLab
- Proofread Translations
- Merging translations from CrowdIn
- Value Stream Analytics development guide
- GitLab subscription
- Activate GitLab EE with a license