The original address: www.cnblogs.com/df88/p/1361…

Skip the installation process. Search a bunch of them online.

introduce

This article will develop a simple Go package in a Module.

It also introduces the Go tool (aka the go command line).

And how to fetch, build, and install Go modules, Packages, commands.

Code organization

Go organizes code in packages. A package == a directory.

Functions, types, variables, and constants are shared in the same package. Package access, which is also the default in Java.

Packages are placed in the module, which is defined by the go.mod file. Typically, a repository has only go.mod, which is placed in the root directory.

You can create this file using go mod init name. After go run, the go.sum file is generated, which contains the encrypted hash of Go.mod.

A repository can also have packages for multiple modules. The packages of a module are the directory in which go.mod resides.

The first program

Suppose the Module path is

example.com/user/hello

.

$ mkdir hello # Alternatively, clone it if it already exists in version control. $ cd hello $ go mod init example.com/user/hello go: Creating new go.mod: module example.com/user/hello $cat go.mod module example.com/user/hello go 1.14 $Copy the code

The first statement in the Go source file must be Package Name. The program entry must be Package Main.

package main

import "fmt"

func main() {
	fmt.Println("Hello, world.")
}
Copy the code

Hello World.

You can now build and install,

$ go install example.com/user/hello
$
Copy the code

This command builds and then generates the executable binaries (this is one of the reasons I prefer Go, which generates the executable directly and saves the hassle of installing dependencies). If the software testing, interface, automation, performance testing, LR script development, interview experience exchange. If you are interested in 1079636098, there will be free information links in the group from time to time. These materials are collected and sorted out from various technical websites. If you have good learning materials, you can send them to me privately, AND I will indicate the source and share them with you.

The build and install commands can both generate executable files. The difference is that

  • Go Build cannot generate package files, but Go Install can generate package files
  • Go Build generates the executable file in the current directory. Go install generates the executable file in the bin directory

Install The bin directory for the build file is based on environment variables. Check in the following order

  • GOBIN
  • GOPATH

If neither is set, the default GOPATH (Linux $HOME/go or Windows %USERPROFILE%\go) is generated.

The example binary file is generated to $HOME/go/bin/hello (%USERPROFILE%\go\bin\hello.exe on Windows).

You can view the values of the environment variables GOBIN and GOPATH

go env
Copy the code

You can also set GOBIN

$ go env -w GOBIN=/somewhere/else/bin
$
Copy the code

After setting, you can reset it

$ go env -u GOBIN
$
Copy the code

GOPATH needs to be modified to the system environment variable.

Commands such as install need to be executed in the source directory, specifically the current working directory. Otherwise, an error will be reported.

Execute in the current directory. The following is equivalent

$ go install example.com/user/hello

$ go install .

$ go install
Copy the code

To verify the results, add the install directory to PATH for convenience

# Windows users should consult https://github.com/golang/go/wiki/SettingGOPATH # for setting %PATH%. $ export PATH=$PATH:$(dirname $(go list -f '{{.Target}}' .) ) $ hello Hello, world. $Copy the code

If the CD is in the bin directory of install, you can also use it directly

$ hello
Hello, world.
$
Copy the code

At present, many Go libraries are hosted on GitHub and other code hosting sites, and are submitted using Git

$ git init Initialized empty Git repository in /home/user/hello/.git/ $ git add go.mod hello.go $ git commit -m "initial  commit" [master (root-commit) 0b4507d] initial commit 1 file changed, 7 insertion(+) create mode 100644 go.mod hello.go $Copy the code

The Go command locates the Repository containing the given Module path by requesting the corresponding HTTPS URL and reading the metadata tags embedded in the HTML response

Bitbucket (Git, Mercurial) import "bitbucket.org/user/project" import "bitbucket.org/user/project/sub/directory" GitHub (Git) import "github.com/user/project" import "github.com/user/project/sub/directory" Launchpad (Bazaar) import "launchpad.net/project" import "launchpad.net/project/series" import "launchpad.net/project/series/sub/directory" import  "launchpad.net/~user/project/branch" import "launchpad.net/~user/project/branch/sub/directory" IBM DevOps Services (Git) import "hub.jazz.net/git/user/project" import "hub.jazz.net/git/user/project/sub/directory"Copy the code

Many hosting sites already provide metadata for Go’s Repository, and the easiest way to share modules is to have the Module path match the Repository URL.

From the module import packages

To reverse the string, create a reverse.go file in the package named Morestrings

// Package morestrings implements additional functions to manipulate UTF-8
// encoded strings, beyond what is provided in the standard "strings" package.
package morestrings

// ReverseRunes returns its argument string reversed rune-wise left to right.
func ReverseRunes(s string) string {
	r := []rune(s)
	for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
		r[i], r[j] = r[j], r[i]
	}
	return string(r)
}
Copy the code

Because the ReverseRunes function is uppercase, it is public and can be imported by other packages.

The build test succeeds

$ cd $HOME/hello/morestrings
$ go build
$
Copy the code

Because it is only in the package, not in the module root directory, go Build does not generate files. Instead, go Build stores the compiled package in the local build cache.

Then import in hello.go

package main import ( "fmt" "example.com/user/hello/morestrings" ) func main() { fmt.Println(morestrings.ReverseRunes("! oG ,olleH")) }Copy the code

Then install the hello

$ go install example.com/user/hello
Copy the code

Validation, import successful, string inversion

$ hello
Hello, Go!
Copy the code

Remore modules import packages from remote

You can use import Path to obtain the source code of a package through a version control system, such as Git or Mercurial.

For an example, use github.com/google/go-cmp/cmp

package main import ( "fmt" "example.com/user/hello/morestrings" "github.com/google/go-cmp/cmp" ) func main() { fmt.Println(morestrings.ReverseRunes("! oG ,olleH")) fmt.Println(cmp.Diff("Hello World", "Hello Go")) }Copy the code

When you run the go install go build go run command, the go command automatically downloads the remote Module and writes it to the go.mod file

$ go install example.com/user/hello go: finding module for package github.com/google/go-cmp/cmp go: Downloading github.com/google/go-cmp v0.4.0 go: Found github.com/google/go-cmp/cmp in github.com/google/go-cmp v0.4.0 $hello Hello, Go! string( - "Hello World", + "Hello Go", ) $cat go.mod module example.com/user/hello go 1.14 require github.com/google/go-cmp v0.4.0 $Copy the code

Domestic timeout is easy, you can use the proxy to access the domestic mirror

Seven NiuYun

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

Ali cloud

go env -w GO111MODULE=on
go env -w GOPROXY=https://mirrors.aliyun.com/goproxy/,direct
Copy the code

Module dependencies are automatically downloaded to the GOPATH directory

pkg/mod

Subdirectories.

Module specifies the version of modules that is downloaded and shared with all other require versions of modules, so the go command marks these files and directories as read-only.

You can use the command to delete all downloaded modules

$ go clean -modcache
$
Copy the code

test

Go has a lightweight testing framework, Go Test and

testing package

.

The test framework recognizes files ending in _test.go that contain

TestXXX

A named function with the function signature func (t * testing.t). If a function call fails such as t. ror or t. ail, test will fail.

Example, New

$HOME/hello/morestrings/reverse_test.go

File to add morestrings package test code

package morestrings import "testing" func TestReverseRunes(t *testing.T) { cases := []struct { in, Want a string} {{" Hello, world ", "dlrow olleH"}, {" Hello, world ", "world, olleH"}, {" ", ""},} for _, c := range cases { got := ReverseRunes(c.in) if got ! = c.want { t.Errorf("ReverseRunes(%q) == %q, want %q", c.in, got, c.want) } } }Copy the code

Run the test

$go test PASS ok example.com/user/morestrings s $0.165Copy the code

If the software testing, interface, automation, performance testing, LR script development, interview experience exchange. If you are interested, you can follow me. There will be free information links in the group from time to time, which are collected and sorted out from various technical websites. If you have good learning materials, you can send them to me privately.