Table of Contents
go module usage
1. Introduction to go module usage
1.1 GO111MODULE
1.2 Republican /proxy.golang.org
go get foo@e3702bed2
go get
Run
go.mod
go mod edit -fmt
Copy after login
" >
go mod edit -fmt
Copy after login
go mod edit -droprequire=package path
golang.org/x/text
Execute
二、包和调用文件在同一项目下
三、包和被调用文件不在同一个项目下
Home Backend Development Golang What is go module? how to use? (with usage examples)

What is go module? how to use? (with usage examples)

Jan 12, 2022 pm 04:02 PM
golang Base

This article is provided by the golang tutorial column to introduce you to the use of go module. I hope it will be helpful to friends in need!

go module usage

go module was launched after go 1.14 version

1. Introduction to go module usage

go module is the version management tool officially launched after Go1.11 version, and starting from Go1.13 version, go module will be the default dependency management tool of Go language.

1.1 GO111MODULE

To enable go module support, you must first set the environment variable GO111MODULE, through which you can turn on or off module support. It has three Optional values: off, on, auto, the default value is auto.

  • GO111MODULE=offDisables module support and will look for packages from the GOPATH and vendor folders when compiling.

  • GO111MODULE=onEnable module support, the GOPATH and vendor folders will be ignored when compiling, only based on go.modDownload dependencies to the %GOPATH%/pkg/mod/ directory.

  • GO111MODULE=auto, when the project is outside $GOPATH/src and the project root directory has go.mod file, enable module support.

Simply put, after setting GO111MODULE=on, you can use go module. There is no need to create projects in GOPATH in the future. , and can also well manage the third-party package information that the project depends on.

After using go module to manage dependencies, two files go.mod and go.sum will be generated in the project root directory.

1.2 Republican /proxy.golang.org

is inaccessible in China, so it is highly recommended that you set up GOPROXY. Here I recommend using goproxy.cn.

export GOPROXY=https://goproxy.cn
Copy after login
1.3 go mod command

Commonly used go modcommands are as follows:

go env -w GOPROXY=https://goproxy.cn,direct
Copy after login
1.4 go.mod

go.mod The file records all the dependency information of the project, and its structure is roughly as follows:

go mod download    下载依赖的module到本地cache(默认为$GOPATH/pkg/mod目录)
go mod edit        编辑go.mod文件
go mod graph       打印模块依赖图
go mod init        初始化当前文件夹, 创建go.mod文件
go mod tidy        增加缺少的module,删除无用的module
go mod vendor      将依赖复制到vendor下
go mod verify      校验依赖
go mod why         解释为什么需要依赖
Copy after login
Among them,

module

is used to define the package name

require
    Used to define dependent packages and versions
  • indirect
  • Indicates indirect reference
  • 1.4.1 Dependent version
  • go mod supports semantic version numbers, such as go get foo@v1.2.3, or it can be followed by git branches or tags, such as
  • go get foo@master
, of course it can also be followed git commit hash, such as

go get foo@e3702bed2

. Regarding dependent versions, the following formats are supported:

module github.com/Q1mi/studygo/blogger

go 1.12

require (
    github.com/DeanThompson/ginpprof v0.0.0-20190408063150-3be636683586
    github.com/gin-gonic/gin v1.4.0
    github.com/go-sql-driver/mysql v1.4.1
    github.com/jmoiron/sqlx v1.2.0
    github.com/satori/go.uuid v1.2.0
    google.golang.org/appengine v1.6.1 // indirect
)
Copy after login
1.4.2 replace Each package accessing golang.org/x in China needs to bypass the firewall. You can go.mod Use replace to replace it with the corresponding library on github.
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7
gopkg.in/vmihailenco/msgpack.v2 v2.9.1
gopkg.in/yaml.v2 <=v2.2.1
github.com/tatsushid/go-fastping v0.0.0-20160109021039-d7bb493dee3e
latest
Copy after login
1.5 go get

Execute the

go get

command in the project to download the dependency package, and you can also specify the downloaded version.

Run

go get -u

will upgrade to the latest minor version or revision (x.y.z, z is the revision number, y is the minor version number)Run

go get -u=patch
    will be upgraded to the latest revision
  1. Run go get package@version
  2. will be upgraded to the specified version No. version
  3. If you download all dependencies, you can use the
  4. go mod download
  5. command. 1.6 Organizing dependencies
After we delete the dependent code in the code, the related dependent libraries will not be automatically removed in the

go.mod file. In this case, we can use the go mod tidy

command to update the dependencies in

go.mod

.

1.7 go mod editFormattingBecause we can manually modify the go.mod file, sometimes we need to format the file. Go provides the following commands:

replace (
    golang.org/x/crypto v0.0.0-20180820150726-614d502a4dac => github.com/golang/crypto v0.0.0-20180820150726-614d502a4dac
    golang.org/x/net v0.0.0-20180821023952-922f4815f713 => github.com/golang/net v0.0.0-20180826012351-8a410e7b638d
    golang.org/x/text v0.3.0 => github.com/golang/text v0.3.0
)
Copy after login
Add dependencies

go mod edit -fmt
Copy after login

Remove dependencies

If you just want to modify the contents of the

go.mod

file , then you can run

go mod edit -droprequire=package path

. For example, if you want to remove the

golang.org/x/text

package in

go.mod, you can Use the following command:

go mod edit -require=golang.org/x/text
Copy after login
More usage of go mod edit can be viewed through go help mod edit. 1.8 Using go module in the project

1.8.1 Existing projectIf you need to enable go module

for an existing project, you can Follow the steps below:

Execute

go mod init

in the project directory to generate a go.mod file.

    Execute
  1. go get to find and record the dependencies of the current project, and generate a go.sum to record the version and hash value of each dependent library.
  2. 1.8.2 New ProjectFor a newly created project, we can follow the following steps under the project folder:<ol> <li>执行<code>go mod init 项目名命令,在当前项目文件夹下创建一个go.mod文件。
  3. 手动编辑go.mod中的require依赖项或执行go get自动发现、维护依赖。

二、包和调用文件在同一项目下

例如:

moduledemo
├── go.mod
├── main.go
└── mypackage
    └── mypackage.go  // package mp 定义包名为 mp
Copy after login

步骤:

1.在项目下创建一个 go.mod 文件,文件名只能为这个。

2.在 go.mod 文件中添加以下代码

module moduledemo  // 设定 moduledemo 为包根目录名,可以随意改变该名字,只需要导入时一致就好
go 1.14  // 表明版本
Copy after login

3.导入想要的包文件

import "moduledemo/mypackage"  // 这里是导入包目录下的包文件名
Copy after login

4.使用包文件

mp.MyPackage()  // 使用包中的 MyPackage() 函数
Copy after login

三、包和被调用文件不在同一个项目下

例如:

├── moduledemo
│   ├── go.mod
│   └── main.go
└── mypackage
    ├── go.mod
    └── mypackage.go  // package mp 定义包名为 mp
Copy after login

步骤

1.在 mypackage 下面创建 go.mod 文件,并添加以下代码

module mypackage

go 1.14
Copy after login

2.在 moduledemo 下面创建 go.mod 文件,并添加以下代码

module moduledemo

go 1.14


require mypackage v0.0.0  // 这个会在你执行 go build 之后自动在该文件添加
replace mypackage => ../mypackage  // 指定需要的包目录去后面这个路径中寻找
Copy after login

3.导入和使用

import "mypackage"  // 因为该包目录本身就是包文件所以无需添加下一级路径

mp.MyPackage()  // 使用包中的 MyPackage() 函数
Copy after login

The above is the detailed content of What is go module? how to use? (with usage examples). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to safely read and write files using Golang? How to safely read and write files using Golang? Jun 06, 2024 pm 05:14 PM

Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

How to configure connection pool for Golang database connection? How to configure connection pool for Golang database connection? Jun 06, 2024 am 11:21 AM

How to configure connection pooling for Go database connections? Use the DB type in the database/sql package to create a database connection; set MaxOpenConns to control the maximum number of concurrent connections; set MaxIdleConns to set the maximum number of idle connections; set ConnMaxLifetime to control the maximum life cycle of the connection.

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

Golang framework vs. Go framework: Comparison of internal architecture and external features Golang framework vs. Go framework: Comparison of internal architecture and external features Jun 06, 2024 pm 12:37 PM

The difference between the GoLang framework and the Go framework is reflected in the internal architecture and external features. The GoLang framework is based on the Go standard library and extends its functionality, while the Go framework consists of independent libraries to achieve specific purposes. The GoLang framework is more flexible and the Go framework is easier to use. The GoLang framework has a slight advantage in performance, and the Go framework is more scalable. Case: gin-gonic (Go framework) is used to build REST API, while Echo (GoLang framework) is used to build web applications.

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

How to find the first substring matched by a Golang regular expression? How to find the first substring matched by a Golang regular expression? Jun 06, 2024 am 10:51 AM

The FindStringSubmatch function finds the first substring matched by a regular expression: the function returns a slice containing the matching substring, with the first element being the entire matched string and subsequent elements being individual substrings. Code example: regexp.FindStringSubmatch(text,pattern) returns a slice of matching substrings. Practical case: It can be used to match the domain name in the email address, for example: email:="user@example.com", pattern:=@([^\s]+)$ to get the domain name match[1].

Golang framework development practical tutorial: FAQs Golang framework development practical tutorial: FAQs Jun 06, 2024 am 11:02 AM

Go framework development FAQ: Framework selection: Depends on application requirements and developer preferences, such as Gin (API), Echo (extensible), Beego (ORM), Iris (performance). Installation and use: Use the gomod command to install, import the framework and use it. Database interaction: Use ORM libraries, such as gorm, to establish database connections and operations. Authentication and authorization: Use session management and authentication middleware such as gin-contrib/sessions. Practical case: Use the Gin framework to build a simple blog API that provides POST, GET and other functions.

How to use predefined time zone with Golang? How to use predefined time zone with Golang? Jun 06, 2024 pm 01:02 PM

Using predefined time zones in Go includes the following steps: Import the "time" package. Load a specific time zone through the LoadLocation function. Use the loaded time zone in operations such as creating Time objects, parsing time strings, and performing date and time conversions. Compare dates using different time zones to illustrate the application of the predefined time zone feature.

See all articles