准备
使用mod之前先检查自己的配置以及go的版本
1.go的版本需要在1.11以上
2.检查go env,需要注意GO111MODULE=on
3.gopath设置成go的安装目录
看看我的配
go mod 命令
命令 | 说明 |
---|---|
download | loaddownload modules to local cache(下载依赖包) |
edit | edit go.mod from tools or scripts(编辑go.mod) |
graph | print module requirement graph (打印模块依赖图) |
init | initialize new module in current directory(在当前目录初始化mod) |
tidy | add missing and remove unused modules(拉取缺少的模块,移除不用的模块) |
vendor | make vendored copy of dependencies(将依赖复制到vendor下) |
verify | verify dependencies have expected content (验证依赖是否正确) |
why | explain why packages or modules are needed(解释为什么需要依赖) |
使用
1.创建文件夹
在你想要进行项目的地方创建文件夹
然后进入该文件夹打开命令行
使用go mod init 项目名 创建go.mod文件
go mod init project
执行了该命令会在该目录下自动生成go.mod文件,内容如下:
module project
go 1.14
2.创建main
创建main.go
package main
import (
"fmt"
"github.com/valyala/fasthttp"
)
func httpHandle(ctx *fasthttp.RequestCtx) {
var path string =string(ctx.Path());
fmt.Printf("%s\n",path);
}
func main() {
fmt.Printf("启动服务\n")
fh := &fasthttp.Server{
Handler: httpHandle,
MaxRequestBodySize: 100 * 1024 * 1024,
}
err := fh.ListenAndServe(":8188");
if err != nil {
fmt.Println("start fasthttp fail:", err.Error())
}
}
然后直接执行:
go run main.go
会自动的下载所需要的依赖包,同时go.mod文件也会发生变化,下载的包会存在gopath下的pkg/mod目录下
module gomodtest2
go 1.14
require github.com/valyala/fasthttp v1.19.0
还会自动生成文件go.sum文件用于记录
github.com/andybalholm/brotli v1.0.0 h1:7UCwP93aiSfvWpapti8g88vVVGp2qqtGyePsSuDafo4=
github.com/andybalholm/brotli v1.0.0/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y=
github.com/klauspost/compress v1.10.7 h1:7rix8v8GpI3ZBb0nSozFRgbtXKv+hOe+qfEpZqybrAg=
github.com/klauspost/compress v1.10.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.19.0 h1:PfTS4PeH3xDr3WomrDS2ID8lU2GskK1xS3YG6gIpibU=
github.com/valyala/fasthttp v1.19.0/go.mod h1:jjraHZVbKOXftJfsOYoAjaeygpj5hr8ermTRJNroD7A=
3.引入自己的go文件
初始化使用的项目名/package名
我这就是 project/funcs
package main
import (
"fmt"
"github.com/valyala/fasthttp"
"project/funcs"
)
func httpHandle(ctx *fasthttp.RequestCtx) {
var path string =string(ctx.Path());
fmt.Printf("%s\n",path);
}
func main() {
fmt.Printf("启动服务\n")
fh := &fasthttp.Server{
Handler: httpHandle,
MaxRequestBodySize: 100 * 1024 * 1024,
}
err := fh.ListenAndServe(":8188");
if err != nil {
fmt.Println("start fasthttp fail:", err.Error())
}
}
最后项目打包之前可以使用go mod tidy命令优化,会自动删除go.mod中没有使用的包
go mod tidy
打包的话使用命令:
go build main.go