最佳的学习方式就是上手实践操作!!!
本文掌握
- 认识 main.go 入口(init、main函数)
- 邂逅 gin 框架,项目路由设置
- 如何安装依赖
认识 init、main 函数
资料3的go基础有详细介绍,这里做个简单说明:
- 都是Go程序自动调用
- 没有参数,没有返回值
- main 只能在入口文件 main 包中,只能定义一个
- init 可以在任意包中应用,且可以重复定义多个
(如果init函数中使用了println()或者print()你会发现在执行过程中这两个不会按照你想象中的顺序执行。这两个函数官方只推荐在测试环境中使用,对于正式环境不要使用。)
下面来测试,修改main.go:
package main
// 引入一个包
import "fmt"
// init 可以应用多次
func init() {
fmt.Println("Hello World1")
}
func init() {
fmt.Println("Hello World4")
}
// 只能应用一次
func main() {
fmt.Println("Hello World2")
fmt.Println("Hello World3")
}
执行go run main.go,打印如下:
Hello World1
Hello World4
Hello World2
Hello World3
邂逅 gin框架
介绍:gin简介
借助框架开发,省时省力。
下面来测试,修改main.go:
package main
// 引用多个包
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
// 两个打印,可以判断执行的先后顺序
fmt.Println("gin1")
// 创建路由
r := gin.Default()
fmt.Println("gin2")
// 绑定路由规则,执行函数
r.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "hello world")
})
r.GET("/gintest", func(c *gin.Context) {
c.String(http.StatusOK, "gin test")
})
// 监听端口,默认:8080
r.Run(":3250")
}
执行go run main.go,会报错!!!
main.go:6:2: no required module provides package github.com/gin-gonic/gin; to add it:
go get github.com/gin-gonic/gin
执行下面的命令,安装依赖包 gin (安装依赖的命令:go get github.com/xxx)
go get github.com/gin-gonic/gin
再次执行 go run main.go,程序启动成功
[GIN-debug] GET / --> main.main.func1 (3 handlers)
[GIN-debug] GET /gintest --> main.main.func2 (3 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Listening and serving HTTP on :3250
在浏览器输入 localhost:3250 地址,网页展示 hello world
在浏览器输入 localhost:3250/gintest 地址,网页展示 gin test
会了吗,一次完美的邂逅~