安装环境
sdk
- 下载地址,之后解压或者安装。
- 设置环境变量:
- 创建GOROOT-sdk根目录:
E:\go\go1.16.5\go
- 修改Path:添加
%GOROOT%\bin
- 创建GOPATH-工作空间:
E:\go\gopath
- 通常gopath下创建3个目录。bin:打包后的exe文件,pkg:第三方包,src:源文件
go version
测试是否安装成功。
goland
开发
创建工程
- 创建goModules。
- go mod相关介绍。类似pom.xml或者build.gradle。
引入依赖
module "demo"
go 1.16
require (
github.com/tidwall/gjson v1.2.2
)
- 根据提示下载包。
go mod download github.com/tidwall/gjson
- 注意设置环境变量GOPROXY开代理:
GOPROXY=https://goproxy.cn
。设置步骤。
业务开发
- 工程目录
my_func.go
为工具类
package pack1
import (
"fmt"
"github.com/tidwall/gjson"
"net/http"
)
func parse(json string, path string) string {
return gjson.Get(json, path).String()
}
func HandleHttp(writer http.ResponseWriter, request *http.Request) {
var json = `{"name":{"first":"Janet","last":"Prichard"},"age":47}`
var path = request.URL.Query().Get("path")
if "" != path {
var pathValue = parse(json, path)
fmt.Fprint(writer, path+": "+pathValue)
} else {
fmt.Fprint(writer, "empty path")
}
}
package main
import (
"fmt"
"demo/pack1"
"net/http"
)
func main() {
http.HandleFunc("/", pack1.HandleHttp)
err := http.ListenAndServe("127.0.0.1:8080", nil)
if err != nil {
fmt.Println(err)
}
}
goland调试
- 如果goland调试时缺少包,使用
go mod tidy
引入。 - 如果delve版本低无法debug,升级delve版本。
打包部署
- go.mod同级目录下命令
go install
,打包之后的exe文件在gopath/bin
下。 - 双击执行,浏览器访问。
参考资料