2018-03-13 Go best practices

Successful Go Program Design, 6 Years On

Development environment

Some Go developers uses a two-entry GOPATH, e.g.
$HOME/go/external:$HOME/go/internal
go get will fetch into the first path, so it can be useful if you need strict separation of third-party vs. internal code.

Top Tip: put $GOPATH/bin in your $PATH, so installed binaries are easily accessible

Repository structure

The basic idea is to have two top-level directories, pkg and cmd. Underneath pkg, create directories for each of your libraries. Underneath cmd, create directories for each of your binaries. All of your Go code should live exclusively in one of these locations.

github.com/peterbourgon/foo/
    circle.yml
    Dockerfile
    cmd/
        foosrv/
            main.go
        foocli/
            main.go
    pkg/
        fs/
            fs.go
            fs_test.go
            mock.go
            mock_test.go
        merge/
            merge.go
            merge_test.go
        api/
            api.go
            api_test.go

All of your artifacts remain go gettable.

Top Tip: put library code under a pkg/ subdirectory. put binaries under a cmd/ subdirectory.

Top Tip: always use fully-qualified import paths. never use relative imports.

Formatting and style

use gofmt, goimports
The go vet tool produces(almost!) no false positives, so you might consider making it part of your precommit hook.

Configuration

12-factor apps encourage you to use environment vars for configuration.
define and parse your flags in func main. Only func main has the right to decide the flags that will be available to the user.

Program design

Good

      foo, err := newFoo(
          *fooKey,
          bar,
          100 * time.Millisecond,
          nil,
      )
      if err != nil {
          log.Fatal(err)
      }
      defer foo.close()

Bad

      // Don't do this.
      cfg := fooConfig{}
      cfg.Bar = bar
      cfg.Period = 100 * time.Millisecond
      cfg.Output = nil
      foo, err := newFoo(*fooKey, cfg)
      if err != nil {
          log.Fatal(err)
      }
      defer foo.close()

Better

      // This is better.
      cfg := fooConfig{
          Bar:    bar,
          Period: 100 * time.Millisecond,
          Output: nil,
      }
      foo, err := newFoo(*fooKey, cfg)
      if err != nil {
          log.Fatal(err)
      }
      defer foo.close()

Even better

      // This is even better.
      foo, err := newFoo(*fooKey, fooConfig{
          Bar:    bar,
          Period: 100 * time.Millisecond,
          Output: nil,
      })
      if err != nil {
          log.Fatal(err)
      }
      defer foo.close()

Top Tip: use struct literal initialization to avoid invalid intermediate state. inline struct declarations where possible.

Top Tip: make the zero value useful, especially in config objects

Top Tip: make dependencies explicit.

Top Tip: loggers are dependencies, just like references to other components, database handlers, commandline flags, etc.

Logging and instrumentation

  1. log only actionable information, which will be read by a human or a machine.
  2. avoid fine-grained log levels - info and debug are probably enough
  3. use structured logging, like go-kit/log
  4. loggers are dependencies

Let’s use loggers and metrics to pivot and address global state more directly. Here are some facts about Go:

  • log.Print uses a fixed, global log.Logger
  • http.Get uses a fixed, global http.Client
  • http.Server, by default, uses a fixed, global log.Logger
  • database/sql uses a fixed, global driver registry
  • func init exists only to have side effects on package-global state

Testing

Top Tip: use many small interfaces to model dependencies

Top Tip: tests only need to test the thing being tested

Dependency management

  1. FiloSottile/gvt
  2. Masterminds/glide
  3. kardianos/govendor
  4. constabulary/gb

Build and deploy

Top Tip: perfer go install to go build

Conclusion

Top tips:

  1. Put $GOPATH/bin in your $PATH, so installed binaries are easily accessible.
  2. Put library code under a pkg/ subdirectory. Put binaries under a cmd/ subdirectory.
  3. Always use fully-qualified import paths. Never use relative imports.
  4. Defer to Andrew Gerrand’s naming conventions.
  5. Only func main has the right to decide which flags are available to the user.
  6. Use struct literal initialization to avoid invalid intermediate state.
  7. Avoid nil checks via default no-op implementations.
  8. Make the zero value useful, especially in config objects.
  9. Make dependencies explicit!
  10. Loggers are dependencies, just like references to other components, database handles, commandline flags, etc.
  11. Use many small interfaces to model dependencies.
  12. Tests only need to test the thing being tested.
  13. Use a top tool to vendor dependencies for your binary.
  14. Libraries should never vendor their dependencies.
  15. Prefer go install to go build.
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市交排,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖音婶,帶你破解...
    沈念sama閱讀 217,657評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件艺栈,死亡現(xiàn)場離奇詭異敢艰,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)诡曙,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來略水,“玉大人价卤,你說我怎么就攤上這事≡ɡ裕” “怎么了慎璧?”我有些...
    開封第一講書人閱讀 164,057評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長驶赏。 經(jīng)常有香客問我炸卑,道長,這世上最難降的妖魔是什么煤傍? 我笑而不...
    開封第一講書人閱讀 58,509評(píng)論 1 293
  • 正文 為了忘掉前任盖文,我火速辦了婚禮,結(jié)果婚禮上蚯姆,老公的妹妹穿的比我還像新娘五续。我一直安慰自己,他們只是感情好龄恋,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,562評(píng)論 6 392
  • 文/花漫 我一把揭開白布疙驾。 她就那樣靜靜地躺著,像睡著了一般郭毕。 火紅的嫁衣襯著肌膚如雪它碎。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,443評(píng)論 1 302
  • 那天,我揣著相機(jī)與錄音扳肛,去河邊找鬼傻挂。 笑死,一個(gè)胖子當(dāng)著我的面吹牛挖息,可吹牛的內(nèi)容都是我干的金拒。 我是一名探鬼主播,決...
    沈念sama閱讀 40,251評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼套腹,長吁一口氣:“原來是場噩夢啊……” “哼绪抛!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起电禀,我...
    開封第一講書人閱讀 39,129評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤幢码,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后鞭呕,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體蛤育,經(jīng)...
    沈念sama閱讀 45,561評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,779評(píng)論 3 335
  • 正文 我和宋清朗相戀三年葫松,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了瓦糕。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,902評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡腋么,死狀恐怖咕娄,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情珊擂,我是刑警寧澤圣勒,帶...
    沈念sama閱讀 35,621評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站摧扇,受9級(jí)特大地震影響圣贸,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜扛稽,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,220評(píng)論 3 328
  • 文/蒙蒙 一吁峻、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧在张,春花似錦用含、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至瘟斜,卻和暖如春缸夹,著一層夾襖步出監(jiān)牢的瞬間痪寻,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評(píng)論 1 269
  • 我被黑心中介騙來泰國打工明未, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留槽华,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,025評(píng)論 2 370
  • 正文 我出身青樓趟妥,卻偏偏與公主長得像,于是被迫代替她去往敵國和親佣蓉。 傳聞我的和親對(duì)象是個(gè)殘疾皇子披摄,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,843評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容