# 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