First, why write this, suitable for whom to read

why

I was going to use egg.js to write servers for Midway, but when I found out that my servers were all 2GB pipes, it was a bit difficult to use Node, so I decided to use a different stack. After preliminary research in Kotlin and GO, I found that GO was more in line with my needs, thus I had the output of this series of notes.

Suitable for food consumption

  1. Don’t know anything about the go stack or the backend
  2. The front end of the class who wants to make something
  3. Node has not satisfied the desire of the front-end students
  4. New students who want to learn how to build a project from 0

Not suitable for the food population

  1. No programming foundation pure white
  2. Go big
  3. The back-end bosses

The expected content

There will be about a dozen articles, and I intend to write a generic template for my own use, which can be quickly cruD later.

The current content is only the initial version, and all the content will be refined after writing, adding and deleting, so that it is better to eat.

Limited to individual applications, if you want to do micro services, you can learn about the OPEN source Kratos framework or IStio of STATION B

How to install go

(1) to download

1. Downloading Go is very simple. If it is Windows or MAC, we can directly go to the official website to download the version we need, and then follow the instructions to install it.

Official website: golang.org/dl/

(2) Configure environment variables

1, the Windows

1.1 System Variables

After installation, the GOROOT variable of the Go language will be automatically configured in the Path column of the system variable with a value of C:\Go\bin. In general, system variables do not need to be modified.

1.2 User Variables

In the user variable column, a GOPATH variable is automatically configured with a default value of %USERPROFILE%\go, and %USERPROFILE%\bin is automatically configured in the Path of the user variable. This GOPATH is our working directory. If you don’t want to use the default path, you can change it, for example:

  1. Create the desired directory and create three subfolders in this directory: bin, PKG, and SRC
  2. Edit GOPATH to change the %USERPROFILE%\go value to a custom directory
  3. Edit the Path of the user variable to change %USERPROFILE%\bin to %GOPATH%\bin.

2, MAC

1.1 the bash

  1. To open.bash_profile, we can edit the file by entering open ~/. Bash_profile or vim ~/. Bash_profile on the terminal

  1. Add a configuration at the end of the configuration file

    export GOPATH=$HOME/go

    export GOBIN=$GOPATH/bin

    export PATH=
    P A T H : PATH:
    GOBIN

  1. Finally source ~/.bash_profile overloads the configuration

  2. Run the go env command to check whether it is modified

2.2 ZSH

The MAC’s default shell is ZSH, so it’s not enough to change the bash configuration file. In this case, open the ZSH configuration file and try again

  1. ZSHRC, we can enter open ~/.zshrc or vim ~/.zshrc in the terminal to edit the file

  2. Add a configuration at the end of the configuration file

    export GOPATH=$HOME/go
    export GOBIN=$GOPATH/bin
    export PATH=$PATH:$GOBIN
    Copy the code
  3. Finally source ~/.zshrc overload configuration

  4. Run the go env command to check whether it is modified

3. Change the Go image and enable the Go mod

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

3.1 What is Go.mod? Go.mod is a new official package management tool introduced in Golang1.11. It is used to solve the problem that there is no local record of the specific version of the dependent package, which facilitates the management of the dependent package.

Go.mod is a Modules, and the official definition of Modules is:

Modules are collections of related Go packages that are units of source code exchange and versioning. The go command directly supports using Modules, including logging and resolving dependencies on other Modules. Modules replaces the old GOPATH – based method to specify which source files to use.

Modules differs from traditional GOPATH in that you don’t need to include subdirectories such as SRC or bin. A source directory or even an empty directory can be used as Modules, as long as it contains the go.mod file.

3.2 GO111MODULE parameters

  1. GO111MODULE=off, the go command line will not support the module function, the way to find dependent packages will be the old version of the vendor directory or GOPATH mode to find.

  2. GO111MODULE=on, the go command line will use modules without looking in the GOPATH directory at all.

  3. GO111MODULE=auto, default. The go command line determines whether to enable module based on the current directory. This case can be divided into two situations:

    (1) The current directory is outside of GOPATH/ SRC and contains the go.mod file. (2) The current file is under the directory containing the go.mod file.

Go env -w GO111MODULE=on

3.3 How to use go.mod in a project?

1. Create a project outside the GOPATH/ SRC directory

Once the go.mod file is created, its contents are fully controlled by Go Toolchain. Go Toolchain modifies and maintains go.mod files while executing various commands, such as Go Get, Go Build, and Go Mod.

The go.mod file provides the keywords module, require, replace, and exclude

  • moduleStatement specifies the name of the package (path)
  • requireStatement specifies the dependency module
  • replaceStatement can replace dependency modules
  • excludeStatement can ignore dependency modules

2. In the current directory, run the go mod init + module name command to initialize the module

After initialization, a go.mod file is generated in the current directory, which is a key file that GO uses to manage packages

** Note 1:** To ensure consistent builds, Go introduced the go.mod file to mark the version of each dependency package. During the build process, the Go command will download the dependencies in Go. mod, and the downloaded dependencies will be cached locally for the next build. Given that downloaded dependencies can be maliciously tampered with by hackers or cached locally, a single go.mod file does not guarantee a consistent build.

To solve this security hazard in the Go Module, the Go development team introduced the go.sum file along with the introduction of Go. mod, which records the hash value of each dependency package. If the hash value of the local dependency package is inconsistent with that recorded in the Go.

Note 2:**go.sum does not require manual maintenance, so don’t worry too much.

** Note 3: Init is not required in the ** subdirectory. All dependencies in the subdirectory are organized in the go.mod file in the root directory

** Note 4:** Using Go’s package management mode, dependent third-party packages are downloaded to $GOPATH/ PKG /mod.

** Note 5: The ** version is specified in go.mod. If not specified in go.mod, the go command automatically downloads the latest version of the dependency in the code. If you use the require statement to specify the package and version in go.mod, the go command will download the package according to the specified path and version.

The first line of the generated go.mod file declares the module name

For example, create a tools.go file under the utils directory

The hello.go file in the root directory can import “hello/utils” to reference utils

package main
 
import (
	"hello/utils"
	"github.com/astaxie/beego"
)
 
func main() {
	utils.PrintText("Hi")
}
Copy the code

3.4 go. Mod command

  • Go mod download Download modules to the local cache. The cache path is $GOPATH/ PKG /mod/cache
  • Go mod Edit is a command version to edit go.mod. For example, go mod edit -fmt go.mod formats go.mod
  • The Go Mod Graph shows dependency graphs between modules
  • Go mod init Initializes modules (such as converting existing DEP managed dependencies)
  • Go mod Tidy adds missing packages and removes unused packages
  • Go mod vendor copies dependencies to the vendor/ directory
  • Go mod verify verifies dependencies
  • Go mod Why explain why packages and modules are needed

Attached: go related commands

  1. Specify the root directory for the module and generate the go.mod file

    go mod init example.com/hello
    Copy the code
  2. Download and add dependencies to the go.mod file

    go build, go test
    Copy the code
  3. View all dependencies under Module

    go list -m all
    Copy the code
  4. Update stable dependencies

    go get rsc.io/sampler
    Copy the code
  5. Clean up useless dependencies

    go mod tidy
    Copy the code
  6. Copy the dependencies to the vendor folder of the project path

    go mod vendor
    Copy the code
  7. Ignore the packages in the cache and only compile with the dependencies in the vendor directory

    go build -mod=vendor
    Copy the code
  8. Verify dependencies and see if they have been modified

    go mod verify
    Copy the code

Note 1: The **go mod command cannot be executed in GOPATH by default because the default value of the GO111MODULE is auto. Default cannot be executed in GOPATH by default because the default value of GO111MODULE is auto. Default cannot be executed in GOPATH by default because the default value of GO111MODULE is auto. This is not done by default in GOPATH, and if it must be done, set the environment variable to ON.

Go: Cannot determine module path for source directory

Initialize the project

(1) New project directory and initialization

1. Create a project directory

First, we can choose a desired folder and create a new project directory under it. We can choose the name of the project directory according to our preference. As shown in the picture below, I created a new project directory named go_server.

2. Initialize the project

The first thing we need to do after creating a new project is to initialize the project and create a new go.mod file to manage dependencies in the project

go mod init myblog-server
Copy the code

A go.mod file is generated

3. Import Gin framework

3.1 What is Gin

Gin is an HTTP Web framework written in Go (Golang). It is an API framework similar to Martini but with better performance than Httprouter and nearly 40 times faster. (Above is the description on the official website)

3.2 Prerequisites

Gin requires Go version 1.6 or higher

3.3 installation gin

go get -u github.com/gin-gonic/gin
Copy the code

Once you’re done, you’ll normally have a file called go.sum in your folder. Its purpose is mentioned above, but it’s usually not a concern, so we’ll skip it for now

4. Create the import file main.go

4.1 Create an import file main.go in the root directory

Enter the following code

package main import ( "fmt" "github.com/gin-gonic/gin" ) func main() { S := gin.Default() S.GET("/", Func (c * gin in the Context) {SAN Antonio SON (200, gin. H {" MSG ":" service startup success "})}) err: = S.R UN (" : "8080) if err! = nil {fmt.println (" Server failed to start!" )}}Copy the code

4.2 Run the go run main.go command in the root directory to Start the service

You can see this by going to localhost:8080 or 127.0.0.1:8080 in your browser