社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
go 中文文档
https://www.kancloud.cn/shuangdeyu/gin_book/949417
1,下载 安装
最近开始学习go,学习大部分基础东西,打算写个博客来练练,巩固一下。
go get -u github.com/gin-gonic/gin
通过go命令来下载的时候,下载失败。(import path does not begin with hostname)
开始最重要的是配置这几个环境目录,否则会无法下载相关的gin包,接下来无法继续运行
最后
通过重新配置GOPATH (项目目录地址) GOROOT (go安装地址)GOBIN (项目目录bin的地址)
需要再GOPATH创建 bin pkg src三个目录
go env 查看环境变量配置情况
查看以上三个目录的地址,一定不能配置错误,否则会下载失败
GOROOT 只到go的安装目录,不需要到go的bin目录
比如你的项目目录为D:go_gin 则需要在这个目录下创建这几个目录
同时运行
go get -u github.com/gin-gonic/gin
在等待程序安装完成之后,需要项目写个main.go查看当前的配置是否完成
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 run main.go之后 出现以下信息就可以在浏览器打开访问 localhost:8080
在运行main.go的时候 一直报错未找到安装包,结果是重复运行 go get -u github.com/gin-gonic/gin 命令 安装完成
PS D:phpgo_ginhellogo> go run .main.go
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)
[GIN-debug] GET /ping --> main.main.func1 (3 handlers)
[GIN-debug] Environment variable PORT is undefined. Using port :8080 by default
[GIN-debug] Listening and serving HTTP on :8080
[GIN] 2019/09/09 - 16:13:40 |[90;43m 404 [0m| 0s | ::1 |[97;44m GET [0m /
[GIN] 2019/09/09 - 16:13:41 |[90;43m 404 [0m| 0s | ::1 |[97;44m GET [0m /favicon.ico
[GIN] 2019/09/09 - 16:13:52 |[90;43m 404 [0m| 0s | ::1 |[97;44m GET [0m /
[GIN] 2019/09/09 - 16:14:24 |[90;43m 404 [0m| 0s | ::1 |[97;44m GET [0m /
记录到访问的路由地址时间等等
go 路由
package main
import (
"log" //下面需要用到log打印 因此需要import引用到
"github.com/gin-gonic/gin"
"net/http" //函数中需要用到http 也需要引用到
)
func main() {
// Engin
router := gin.Default()
//router := gin.New()
router.GET("/hello", func(context *gin.Context) {
log.Println(">>>> hello gin start <<<<")
context.JSON(200, gin.H{
"code": http.StatusOK,
"success": true,
})
})
router.GET("/index", func(context *gin.Context) {
log.Println(">>>> hello gin start <<<<")
context.JSON(200, gin.H{
"code": http.StatusOK,
"success": "this is the first time use router",
})
})
router.GET("/english", func(context *gin.Context) {
log.Println(">>>> hello gin start <<<<")
context.JSON(200, gin.H{
"code": http.StatusOK,
"success": "welcome",
})
})
// 指定地址和端口号
router.Run("localhost:9090")
}
go 获取路径中的参数
package main
import (
// "log"
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
// 此规则能够匹配/user/john这种格式,但不能匹配/user/ 或 /user这种格式
router.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})
router.GET("/index", func(c *gin.Context) {
name := "klay"
c.String(http.StatusOK, "Hello %s", name)
})
// 但是,这个规则既能匹配/user/john/格式也能匹配/user/john/send这种格式
// 如果没有其他路由器匹配/user/john,它将重定向到/user/john/
router.GET("/user/:name/*action", func(c *gin.Context) {
name := c.Param("name")
action := c.Param("action")
message := name + " is " + action
c.String(http.StatusOK, message)
})
router.Run(":8080")
}
安装mysql
go get github.com/go-sql-driver/mysql
安装之后,参考博客
https://studygolang.com/articles/14503
把代码copy下来,然后试着跑了一遍,相当于是熟悉一下整个流程
这里遇到几个问题:
1,由于第一次写这个 老是用之前的运行单文件的方法,go run main.go 结果老是报错,这个需要go bulid,之后直接运行生成的exe文件就好
2,可能是我的go env的环境变量的设置问题 GOPATH问题 我把我的 src pkg bin 三个包又装在了一个gin的目录下 类似于 gin/src 按照常规的目录应该是当前的main.go 和src平行的 我的目录为
所以在加载一些包的时候,会有一些问题,也可能是我第一次写这个,所以问题比较多
但是我直接在import引用包的时候,直接加上 ../ 或者 ./ 的方法引用了相应的目录下的包
而在调用相对应的包的方法时,因为用这样的路径的问题,所以在调用方法之前加上 引用的目录名字
PS :因为目前是在本地开发,暂时不知道这样的环境放到linux会有什么样的结果。所以,希望能有人指正。
3,最后报错本地环境 我直接用的phpstudy连接mysql
4,想在接受post参数的时候加个参数验证,结果一直报错
go mismatch: 2 varaiable but c.request.value return 1 values
结果一看代码 把接受的参数写成了 name, err = c.Request.FormValue("first_name") 这种格式不被允许
最后把验证改成了
func AddPersonApi(c *gin.Context) {
firstName := c.Request.FormValue("first_name")
lastName := c.Request.FormValue("last_name")
if firstName == "" || lastName == "" {
msg := fmt.Sprintf("name is not empty")
c.JSON(http.StatusOK, gin.H{
"msg": msg,
})
return
}
p := models.Person{FirstName: firstName, LastName: lastName}
ra, err := p.AddPerson()
if err != nil {
log.Fatalln(err)
}
msg := fmt.Sprintf("insert successful %d", ra)
c.JSON(http.StatusOK, gin.H{
"msg": msg,
})
}
这样写下来可能代码不好看,但是 只能先用判断为空来做验证
开始用的gin写了点东西,现在想改成iris来继续写下去
下载包的时候整了很久,各种下载下来缺少文件 没有vpn的孩纸???
1,
package main
import (
"github.com/kataras/iris"
)
func main() {
app := iris.New()
app.RegisterView(iris.HTML("./web/views", ".html"))
app.Get("/", func(ctx iris.Context) {
ctx.ViewData("message", "hello world!")
ctx.View("index.html")
})
app.Run(iris.Addr(":8080"))
}
<html>
<head>
<titla>测试</title>
</head>
<body>
<h1>{{.message}}</h1>
</body>
</html>
启动成功iris go
2,分目录进行开发 路由router,配置config, 控制器controller, 模型 models, 数据库databases等等
3,
3.1 引入go-toml文件 github.compelletiergo-toml
关于go-toml配置的详细说明https://studygolang.com/articles/12032?fr=sidebar
3.2 引入mysql
github.comgo-sql-drivermysql
3.3 引入gorm https://github.com/jinzhu/gorm orm的框架有很多,甚至很多人自己搭建了自己的框架,其实这就是一个程序和数据库之间的一个中间层,gorm是golang的一个orm框架。
关于gorm的详细解释 https://blog.csdn.net/Hanani_Jia/article/details/87554833
3,4 引入validator包 地址 https://github.com/go-playground/validator/tree/v9.30.0 详细解释见下方
https://blog.csdn.net/biello/article/details/87856942
3,5 引入 jwt https://github.com/dgrijalva/jwt-go
关于jwt https://blog.csdn.net/wangshubo1989/article/details/74529333
3,6 引入 bcrypt https://github.com/jameskeane/bcrypt
关于go的加密方式 https://studygolang.com/articles/15642?fr=sidebar
3,7 引入 middleware
https://github.com/iris-contrib/middleware
3,8 引入 https://github.com/betacraft/yaag
4,关于在代码中遇到的一些参数问题
4,1 os.args 的解释
https://www.jianshu.com/p/64aa578bae9a
4,2 strings.Contains(k,'t') 判断某个参数在不在数组中
4,3 panic 抛出错误的自带的go 内置方法 详细解释见下面博客
https://www.jianshu.com/p/0cbc97bd33fb
4,4 reflect 通过反射获取反射就是一种检查接口变量的类型和值的机制。
可以通过reflect.TypeOf和reflect.ValueOf来得到接口变量的Type和Value,同样可以通过reflect.Value轻松得到reflect.Type
详细解释如下
https://www.cnblogs.com/itbsl/p/10551880.html
4.5 gorm 链接数据库失败,检查数据库是否Running: sql: unknown driver "mysql" (forgotten i mport?)
引入的文件 导入这个 _ "github.com/jinzhu/gorm/dialects/mysql"
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!