Go Tips Tracks

Go Tips Tracks

Go Tips

  • Go Tip #1: Go’s Package Management and Module Systems

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    > A package manager is a tool for automating the process of building
    > in 2018, Go team finally introduced Go modules Go 1.11 but wasn't enabled by default. To turn it on, $ GO111MODULE = on, Go 1.14, modules are now enabled by default

    # GOPATH (Go workspace)
    > assumed $HOME/go on Unix system, %USERPROFILE%\go on Windows
    > As of Go v1.13, $GOPATH mechanics is now largely irrelevant(无关紧要).

    # Getting started with Modules
    $ go mod init <module name> (The module name doubles as the import path, which allows internal imports to be resolved inside the module.)

    # Installing dependencies
    $ go get k8s.io/client-go@latest (adds a new dependency )
    $ go get -u <> (-u=patch to upgrade a dependency to a new minor or patch version)
    // indirect comment indicates that this package is not currently being used in the project

    $ go mod tidy (cleans up unused dependencies or adds missing depenencies)
    $ go mod vendor (create a vendor directory in your project root. all the project dependencies (direct and indirect) required to build your project are copied over to the directory)
    $ go build (compile packages and dependencies)

    # Using replace in go.mod to point to your local module
    > point to the local version of a dependency in Go rather than the one over the web, use the replace keyword.
    $ go mod edit -replace github.com/pselle/bar=/Users/pselle/Projects/bar
  • Go Tip #2: Go module proxy

    1
    2
    3
    4
    5
    6
    7
    8
    9
    > Goproxy.cn has fully implemented the GOPROXY protocol. provide a free, trusted, always on, and globally CDNed Go module proxy for Gophers in China.

    $ go env -w GO111MODULE=on
    $ go env -w GOPROXY=https://goproxy.cn,direct

    # Linux
    $ echo "export GO111MODULE=on" >> ~/.profile
    $ echo "export GOPROXY=https://goproxy.cn" >> ~/.profile
    $ source ~/.profile
  • Go Tip #3: GOPATH, GOROOT, GOBIN

    1
    2
    3
    4
    5
    6
    7
    8
    # GOPATH: is the root of the workspace and contains the following folders
    - src : location of source files: .go,.c,.g,.s
    - pkg : location of compiled packages (.a files)
    - bin : location of executables built by Go
    # GOBIN:
    > The directory where **go install** and **go get** will place binaries after building main packages.
    # GOROOT:
    > The location of your Go installation. It is used to find the standard libraries.
  • Go Tip #4: Go Version Management goenv

    1
    2
    # goenv
    -