当前位置:网站首页>Golang (1) | from environmental preparation to quick start
Golang (1) | from environmental preparation to quick start
2022-07-05 21:06:00 【Xiao Zhu tear code trace】
List of articles
- Preface
- GO A basic introduction to language
- GO Language development environment configuration
- GO Get started quickly
- GO Language multi version and package management
- Standard library -fmt library
- GO Language commonly used management commands
- GO Summary of common language errors
- encounter Windows Files on Linux There is a format error when running on
- obtain GO Wrong time
- environment variable GOPROXY Modification of ( It mainly solves the problem of slow download )
- perform go mod tidy Times wrong
- After importing the package, you need to use , If it is not used, an error will be reported !!
- Input ctrl+] Cannot jump to source
Preface
This column
Will teach you how to achieve zero foundationOne adoption REST style +JSON Built API The server
, This is a Go API A combination commonly used in development , This mode can meet most demand scenarios . It shows through actual combat API Each process in the construction process ( Get ready -> Design -> Development -> test
[ Optional ] -> Deploy ) Implementation method .
Outline presentation
GO A basic introduction to language
Go Characteristics of language
Go Language ensures the security and performance of statically compiled languages , It also achieves the speed and maintainability of dynamic language development , It's been described Go Language : Go = C + Python
, explain Go Language both Yes C The speed of static language programs
, It can reach Python The rapid development of dynamic language
.Go The languages are as follows
characteristic :
- Automatic garbage collection : C/C++ The biggest headache is the pointer problem , If you are not careful, the pointer will go wild or cross the boundary again . stay Go Don't worry about language anymore , Don't worry delete or person free,
The system will automatically recycle
. - Function can return multiple values : This is amazing , Most languages can only return one value ,
Go Languages can return multiple values
. This function makes developers no longer have to think hard about how to return value design , There is no need to define a structure for value transfer . - Concurrent programming : Go Language is naturally concurrent , Just the keywords “go” Can
Let the function execute concurrently
, Make concurrent programming easier , This is also Go The greatest advantage of language . - No dependence on hell , Even glibc
- Compile once , Copy anywhere , Deployment is extremely convenient : Don't look like python The project also needs to install the required dependencies ,GO The deployment of the project is simple 、 quick !
GO Language development environment configuration
Go Installation
Go There are many ways to install , Such as :Go Source code installation 、Go Standard package installation 、 Third party tools (yum、apt-get etc. ) install
Introduction of two environment variables :
GOROOT:GOROOT Namely Go Installation path for
GOPATH:GOPATH It is the storage destination of compiled binary and import The search path of the package ( In fact, it's yoursworking directory , Deposit GO Path to file
)
GOPATH Detailed explanation
go_code // ( example go_code by GOPATH Catalog )
-- bin // golang Compile executable file storage path , Can automatically generate .
-- pkg // golang Compilation of *.a Intermediate file storage path , Can automatically generate .
-- src // go Source path . according to golang Default Convention ,go run,go install The current working path of the command ( That is, on this road Execute the above command directly )
Linux Lower installation GO
- Get the installation package
$ yum install wget -y
$ wget https://golang.google.cn/dl/go1.18.3.linux-amd64.tar.gz
$ tar -xzvf go1.18.3.linux-amd64.tar.gz
$ mv go /usr/local/
- Set the environment variable
stay
~/.bashrc
Add GOPATH Variable
# The installation directory
export GOROOT=/usr/local/go
# Code directory
export GOPATH=~/code
export PATH=$PATH:$GOPATH:$GOROOT/bin
# Be careful : If you have installed it before, you want to choose the latest version
export PATH=$PATH:$GOROOT/bin:$GOPATH
When I'm done , Save the file , And implement
source ~/.bashrc
- Test for successful installation
$ go version
go version go1.18.3 linux/amd64
notice go version Command output go Version number go1.10.2 linux/amd64 , explain go Command installed successfully .
Mac Platform installation GO
$ brew install go
$ go version
go version go1.18.3 darwin/amd64
Windows Platform installation GO
download
Download path :https://golang.google.cn/dl/go1.18.3.windows-amd64.msiinstall msi file
Add the installation path to the environment variable
Such as :go The installation to D:\GO_APP
Add environment variables GOPATH ( Code storage directory )==》D:\GO_code
Add environment variables GOROOT( Software installation directory ) ==》 D:\GO_APP
And add%GOPATH%\bin
To PATH
And add%GOROOT%\bin
To PATH
- Check whether the installation is successful
open cmd Command line , Inputgo version
IDE Installation
Linux platform Vim To configure : Vim yes Linux The most basic tool developed under , You can configure a Vim IDE. We can use open source installation tools , Here, you can directly use this tool to realize one click configuration , The specific configuration steps are as follows :
- download Vim Configuration tool
$ yum install git -y # It is best to enter /tmp Install under
$ git clone https://github.com/lexkong/lexVim
- Get into lexVim Catalog , download go ide The required binaries
$ cd lexVim
$ git clone https://github.com/lexkong/vim-go-ide-bin
It's all binary files , File size , Please be patient !
- Start the installation script
$ ./start_vim.sh
After starting , Will enter an interactive environment , Input in sequence : 1 ==> user name ==》 mailbox ( You can input any ). The script finally outputs this vim config is success ! Description installation successful . It's simple , just 3 You can choose to install successfully , To configure IDE so easy.
If the installation package is downloaded too slowly , But a private letter asks me for a compressed package
## decompression zip Compressed package
# install zip
yum install unzip -y
# decompression zip file
unzip start_vim.sh
## encounter Windows Files on Linux There is a format error when running on
[[email protected] lexVim]# sh start_vim.sh
start_vim.sh: That's ok 9: $'\r': Command not found
start_vim.sh: That's ok 11: $'\r': Command not found
start_vim.sh: That's ok 12: Unexpected symbols `$'\r'' There are grammar errors nearby 'tart_vim.sh: That's ok 12: `function prompt()
# terms of settlement
yum install dos2unix
# transformation
dos2unix start_vim.sh
Vim IDE Common functions
- Jump to the source code :ctrl+] or gd
- Jump out of the source code :ctrl+o
- Jump to the end :shift+G
- Delete all :d+gg
- Delete a line :d
- < F1> Open help , :q sign out
- < F2> Open the directory window , Press again to close the directory window
- < F4> List of recent documents , :q sign out
- < F6> Add function comments
- stay vim Paste text in , need
:set paste
It can be pasted normally
Test tool installation
Linux platform Curl Tools
$ yum install curl
Usage method :
https://www.ruanyifeng.com/blog/2011/09/curl.html
https://www.ruanyifeng.com/blog/2019/09/curl-reference.html
Windows platform APIPOST install
Download address :https://www.apipost.cn/?utm_source=10039&bd_vid=10756414022759907776
GO Get started quickly
- Create a .go The file of
// Declare the package where the file is located , If it is the main program, it is main
package main
// Import library ,fmt Used to process standard input and output
import "fmt"
// main Function is the entry to the whole program ,main The package name of the function must also be `main`
func main() {
// call fmt Bag Println Method , Output information on the screen
fmt.Println("Hello World!")
}
Be careful :
Single-line comments : //
Multiline comment :/* sth */
- Run code
Direct operation
$ go run first.go
Hello World!
Compile first and execute
$ go build first.go
$ ./first
- GO Language configuration
Go It's a compiled language ,Go The tool chain of language converts the source code and its dependencies into the machine instructions of the computer ( Translation notes : Static compilation )
# Set up module management model
$ go env -w GO111MODULE=on
# Set download source
$ go env -w GOPROXY=https://goproxy.cn
## China's most reliable Go Module agent :https://goproxy.cn
# modify env
## echo "export GOPROXY=https://goproxy.cn" >> ~/.profile && source ~/.profile
Try to deploy GO project
- Write code
package main
import (
"fmt"
"github.com/jinzhu/configor"
)
func main() {
fmt.Println("vim-go",configor.Config{
})
}
- Initialize project : It mainly solves the problem of package management dependency
# initialization
go mod init account
# Solve the problem of dependence ( Check , Delete the wrong or unused modules, Did you download it download Of package)
go mod tidy
- function
# go run proj.go
vim-go {
false false false false 0s <nil> false}
GO Language multi version and package management
go module
GOMODULE In mode :
- All dependent packages are stored in GOPATH/pkg/mod Under the table of contents
- All third-party binary executables are placed in GOPATH/bin Under the table of contents
- The project can be placed in GOPATH Out of the path
- It is required that go.mod file ( The document passed go mod init Command initialization can generate )
GOMODULE Patterns and GOPATH The same pattern specifies the location of the dependent package , The difference lies in GOMODULE Of go.mod The specific version of the dependent package is recorded in the file , It realizes the reuse of dependent packages between projects , And solved GOPATH In this mode, different projects cannot rely on different versions of the same package
problem
1. Use GO MODULE Pattern , You need to start the configuration first
$ export GO111MODULE=on
or
$ go env -w GO111MODULE=on
Be careful : After the module support is turned on , Not with GOPATH coexistence , Therefore, the project cannot be placed in GOPATH Under the table of contents !!
About GO111MODULE If you are interested, please refer to this article : The article links
go mod Use of commands
# Initialize working directory -> Generate go.mod file
$ go mod init code
$ go mod tidy
# download gin, Download to pkg Catalog
$ go get github.com/gin-gonic/gin
Common commands
$ go get golang.org/x/tools/cmd/guru
$ go build golang.org/x/tools/cmd/guru
$ mv guru $(go env GOROOT)/bin
Standard library -fmt library
fmt Is a common library for input and output , You can refer to the official website :GO Chinese official website
stay fmt package , There are two kinds of methods for formatting input and output : Scan ( Input function ) and Print ( Output function ), Respectively in scan.go and print.go In file
GO Language commonly used management commands
- go version: obtain Go edition
- go env: see Go environment variable
- go help: see Go Help order
- go get: Get remote package ( It needs to be installed in advance git or hg)
- go build: Compile and generate executable programs
- go run: Run the program directly
- go fmt: Format source code
- go install: Compile the package file and the whole program
- go test: go Unit test commands provided by native
- go clean: Remove the files compiled and generated in the current source package and the associated source package
- go tool: upgrade Go version , Fix old code
- godoc -http:80: Open a local 80 Port of web file
- gdb Executable name : debugging Go Compiled file
GO Summary of common language errors
encounter Windows Files on Linux There is a format error when running on
[[email protected] lexVim]# sh start_vim.sh
start_vim.sh: That's ok 9: $'\r': Command not found
start_vim.sh: That's ok 11: $'\r': Command not found
start_vim.sh: That's ok 12: Unexpected symbols `$'\r'' There are grammar errors nearby 'tart_vim.sh: That's ok 12: `function prompt()
# Download tool
yum install dos2unix
# transformation
dos2unix zjh.sh
# Add executable rights
chmod -x file name
./ file name # It can be carried out ( No suffix )
obtain GO Wrong time
[[email protected] code]# go get golang.org/x/tools/cmd/guru
go: go.mod file not found in current directory or any parent directory.
'go get' is no longer supported outside a module.
To build and install a command, use 'go install' with a version,
like 'go install example.com/[email protected]'
For more information, see https://golang.org/doc/go-get-install-deprecation
or run 'go help get' or 'go help install'.
## resolvent
go mod init mycode # Initialize the directory mod Directory of patterns
environment variable GOPROXY Modification of ( It mainly solves the problem of slow download )
echo "export GOPROXY=https://goproxy.cn" >> ~/.profile && source ~/.profile
# https://goproxy.cn It is the most reliable in China Go Module agent
perform go mod tidy Times wrong
appear go mod tidy newspaper "all" matched no packages The reason is go.mod And execution go mod tidy The directory is not in a directory
[[email protected] proj01]# go mod tidy # Help me install the dependent packages used
go: warning: "all" matched no packages
After importing the package, you need to use , If it is not used, an error will be reported !!
[[email protected] proj01]# go run proj.go
# command-line-arguments
./proj.go:6:2: imported and not used: "github.com/gin-gonic/gin"
Input ctrl+] Cannot jump to source
$ go get golang.org/x/tools/cmd/guru
$ go build golang.org/x/tools/cmd/guru
$ mv guru $(go env GOROOT)/bin
边栏推荐
- Écrire une interface basée sur flask
- @Validated基础参数校验、分组参数验证和嵌套参数验证
- int GetMonth( ) const throw( );后面的throw( )什么意思?
- Add ICO icon to clion MinGW compiled EXE file
- Clickhouse copy paste multi line SQL statement error
- 模式-“里氏替换原则”
- PVC plastic sheets BS 476-6 determination of flame propagation properties
- ViewRootImpl和WindowManagerService笔记
- Arcgis\qgis no plug-in loading (no offset) mapbox HD image map
- Matplotlib drawing retouching (how to form high-quality drawings, such as how to set fonts, etc.)
猜你喜欢
EN 438-7建筑覆盖物装饰用层压板材产品—CE认证
The development of research tourism practical education helps the development of cultural tourism industry
ArcGIS栅格重采样方法介绍
基于AVFoundation实现视频录制的两种方式
CLion配置visual studio(msvc)和JOM多核编译
产品好不好,谁说了算?Sonar提出分析的性能指标,帮助您轻松判断产品性能及表现
Learning robots have no way to start? Let me show you the current hot research directions of robots
[case] Application of positioning - Taobao rotation map
【案例】元素的显示与隐藏的运用--元素遮罩
Using webassembly to operate excel on the browser side
随机推荐
MYSQL IFNULL使用功能
Learning robots have no way to start? Let me show you the current hot research directions of robots
R语言【数据管理】
The reason why the ncnn converted model on raspberry pie 4B always crashes when called
Write an interface based on flask
Pytorch实战——MNIST数据集手写数字识别
postgres 建立连接并删除记录
Add ICO icon to clion MinGW compiled EXE file
Vant source code parsing event Detailed explanation of TS event processing global function addeventlistener
研學旅遊實踐教育的開展助力文旅產業發展
MySQL ifnull usage function
示波器探头对测量带宽的影响
Aitm2-0002 12s or 60s vertical combustion test
MySQL deep paging optimization with tens of millions of data, and online failure is rejected!
R language [data management]
Traps in the explode function in PHP
selenium 获取dom内属性值的方法
Dictionary tree simple introductory question (actually blue question?)
国外LEAD美国简称对照表
SYSTEMd resolved enable debug log