go mod使用及goland配置

本文介绍了Go语言1.12版本后使用`go mod`进行依赖包管理的方式,对比了旧版本的不便,并提供了设置国内源加速的方法,特别是对于Goland用户,详细说明了如何在2019版及以上创建新项目,配置gopath以及goproxy,以优化开发体验。通过示例展示了`go mod`如何自动下载并初始化`go.mod`文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.依赖包管理

python有pip方便第三方包管理,java拥有maven管理。

go在旧版本中可以使用go get 命令获取第三方包, 但是偶尔第三方也存在依赖,这样包管理不是很方便

在go 1.12版本后,增加了go mod 来进行依赖包管理, 方便了许多,因此建议使用1.12以上版本(可自行到官网下载)

查看版本

> go version
go version go1.13.9 windows/amd64


>go mod
Go mod provides access to operations on modules.

Note that support for modules is built into all the go commands,
not just 'go mod'. For example, day-to-day adding, removing, upgrading,
and downgrading of dependencies should be done using 'go get'.
See 'go help modules' for an overview of module functionality.

Usage:

        go mod <command> [arguments]

The commands are:

        download    download modules to local cache
        edit        edit go.mod from tools or scripts
        graph       print module requirement graph
        init        initialize new module in current directory
        tidy        add missing and remove unused modules
        vendor      make vendored copy of dependencies
        verify      verify dependencies have expected content
        why         explain why packages or modules are needed

Use "go help mod <command>" for more information about a command.

二. 包的第三方加速

python 可以使用pip使用国内源地址, 同样go 设置goproxy可以使用国内进行加速:

>go env
set GO111MODULE=
set GOARCH=amd64
set GOBIN=
set GOPROXY=https://proxy.golang.org,direct

设置阿里源进行加速:

>set GOPROXY="https://mirrors.aliyun.com/goproxy/"

>go env
set GO111MODULE=
set GOARCH=amd64
set GOBIN=
set GOPRIVATE=
set GOPROXY="https://mirrors.aliyun.com/goproxy/"

或者使用goproxy中国

set  GOPROXY="https://goproxy.cn"

三. goland 使用gomod

goland建议使用2019以上版本

  1. file -> new project
  2. 选择vgo, 设置工程地址
  3. 配置proxy地址: https://goproxy.cn

在这里插入图片描述
在这里插入图片描述

  1. (可选) 可以设置gopath,设置全局路径和项目专属的路径

    设置方法

    setting -> go -> go path
    在这里插入图片描述

新建main.go 文件,使用gin 编写示例代码, 然后run, go mod会下载依赖包,并初始化go.mod文件, go.mod 文件为项目依赖的包文件配置

package main

import "github.com/gin-gonic/gin"

func main() {
    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })
    r.Run() // listen and serve on 0.0.0.0:8080
}

运行效果如下

go.mod中有依赖的第三方包配置信息
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值