Go language introduction and technical guide

table of Contents

Environmental installation


Go language

Introduction to Go language-Goland etc.  http://c.biancheng.net/view/6124.html
Go by Example Chinese :  https://books.studygolang.com/gobyexample/
Golang standard library documentation:   https://studygolang.com/pkgdoc

Environmental installation overview

There are two versions of the installation package for windows and linux. The following is a screenshot of the installation package:

Pay attention to the distinction between $GOROOT and $GOPATH in the configuration variables, they can be the same directory, in many cases different paths

$GOROOT is the initial path of the system environment. It is the basic environment for the operating system to compile go. It is generally a relatively clean official package program directory, and it is best not to modify it easily;

$GOPATH is the path of the application environment, used to store the application environment and the extended environment of the third-party package

Install go in windows environment

After the windows installation package is installed, it is best to specify the installation directory as drive d, and the current installation directory is d:\go. After the installation is complete, the system can directly run go env by default to view the environment installation directory. The GOPATH path can set environment variables, as follows :

It indicates that the go environment has been successfully installed.

Simply write and run a go program hello world, the code is as follows

package main import "fmt" func main() {	fmt.Println("hello go 2012")	var i string	fmt.Scan(&i)	fmt.Println("获取到的内容", i)}

The running command is: go run xx/main.go, as follows:

Install go in linux environment

# wget https://dl.google.com/go/go1.16.1.linux-amd64.tar.gz

# tar -C /usr/local -zxvf go1.16.1.linux-amd64.tar.gz

vim /etc/profile
// Add
export GOROOT=/usr/local/go in the last line
export PATH=$PATH:$GOROOT/bin
// After saving and exiting wq source,
source /etc/profile

View version

# go version

Install git

Download git installation directly under windows no longer explain

The linux installation is as follows:

# yum -y install git

# git --version

Download and install dependent packages

When downloading go's dependent packages, it will fail, and the parameters need to be adjusted. Possible approaches are as follows:

View the environment

# go env

Modify agent environment parameters

# go env -w GOPROXY=https://goproxy.cn,direct

Windows
open your PowerShell and execute:

C:> $env:GOPROXY = " https://goproxy.cn "

Install third-party dependency packages, such as gorm

# go get -u gorm.io/gorm

We find where this dependency package is placed

It is found that it is placed under /root/go/pkg/mod, and the default download dependency package is placed here

We look at the go environment parameters and we will understand

If we develop under windows, we can copy this package to the development package directory (under windows, the process of being walled may fail, we will download through linux and copy it)

Points to note in go language

Use of the package

1. Click operation Sometimes you will see the following way to import a package import (. "Fmt")  
This point operation means that after the package is imported, when you call the function of this package, you can omit the package name of the prefix, which is The fmt.Println("hello world") you called earlier can be omitted and written as Println("hello world")
2. Alias ​​operation Alias ​​operation, as the name implies, can name the package into another name that is easy to remember
       import( f "fmt" ) When the alias operation calls the package function, the prefix becomes the renamed prefix, that is, f.Println("hello world")
3. _operation This operation is often an operator that is confusing to many people. Please see the following import
     import ( "Database/sql" _ "github.com/ziutek/mymysql/godrv")

Point operation package

package main import (. "fmt") func main()  {	Println("直接调用当前包函数") }

_Operation package

package main import (	"fmt"	_ "yunyan/test/models"	) func init(){	fmt.Println("_操作 初始化init方法")} func main(){	fmt.Println("_操作调用包")}

Null operator_

nums := []int{2, 3, 4}sum := 0for _, num := range nums {	sum += num}fmt.Println("sum:", sum)

IDE development tools

Recommend JetBrains GoLand

Gin framework

Introduction

Gin  is a  golang  micro-framework with elegant encapsulation,  friendly API  , clear source code comments, fast and flexible, and convenient fault tolerance; For  golang  ,  the dependency of web  frameworks is much  smaller than that of Python  and  Java  . Its own  net/http  is simple enough and its performance is also very good With the help of framework development, not only can save a lot of time brought by commonly used packaging, but also help the team's coding style and formation of norms Document address:  https://github.com/gin-gonic/gin Suggestion: The gin framework and the laravel framework are somewhat similar, we can learn and use according to the laravel framework idea.

installation

Install it in accordance with the method of installing third-party dependency packages (described earlier) # go get -u github.com/gin-gonic/gin

Example

Example 1: Web access interface

Create the file gin-frame/example.go

package mainimport "github.com/gin-gonic/gin" func main() {	r := gin.Default()	r.GET("/index", func(c *gin.Context) {		c.JSON(200, gin.H{			"message": "ok",		})	})	r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")}

Start and run this example.go as a service listener # go run example.go

Browser access: http://127.0.0.1:8080/index

Example 2: Database orm access The dependency package gorm needs to be installed first # go get -u gorm.io/gorm Create a database locally, named db_go_shop, create a test table, test data, as follows

CREATE TABLE `tp_goods` (  `goods_id` int(11) NOT NULL AUTO_INCREMENT,  `goods_name` varchar(100) NOT NULL,  `shop_id` int(11) NOT NULL,  `category_id` int(5) DEFAULT NULL,  PRIMARY KEY (`goods_id`)) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4; -- ------------------------------ Records of tp_goods-- ----------------------------INSERT INTO `tp_goods` VALUES ('1', '花生', '1', '1');INSERT INTO `tp_goods` VALUES ('2', '牛奶', '1', '1');

The directory structure is as follows:

goods.go

package models import "gorm.io/gorm" type Goods struct {	gorm.Model	GoodsId    int `gorm:"primarykey"` //对应表中的字段名 goods_id	ShopId     int	CategoryId int	GoodsName  string}

models.go

package models import (	"fmt"	"gorm.io/driver/mysql"	"gorm.io/gorm"	"gorm.io/gorm/schema") var (	dsn string = "root:[email protected](localhost:3306)/db_go_shop?charset=utf8mb4") func DB() *gorm.DB {	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{		NamingStrategy: schema.NamingStrategy{			TablePrefix:   "tp_",			SingularTable: true,		},	})	fmt.Println("err : ", err)	return db}

models_test.go

package models import (	"fmt"	"testing") func TestGetGoods(t *testing.T) {	where := map[string]interface{}{		"goods_id": 1,	}	var goods Goods	DB().Debug().Where(where).Unscoped().Find(&goods)	fmt.Println("goods : ", goods)}

Test run (under the current code directory)

# go test -v

Query the database and return the result.