[图片上传失败...(image-ce8666-1617109389674)]
安装:
下载并安装
go get -u github.com/gin-gonic/gin
github.com/gin-gonic/ginGOPATHgithub.com
image
遇到的报错信息:
Go 项目编译:cannot find package "." in:*******
将缺少依赖的包重新安装一次即可解决问题。
go: inconsistent vendoring in xxx报错
image
修改GOPAHT,改到非GOROOT路径。GOROOT是GO语言安装路径,GOPATH是GO语言编译环境所需路径,因此二者不能为同一路径
image
新建项目
GOPATH
go mod init
main.go
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{
"name": "叫我詹躲躲",
"gend": "男",
})
})
r.Run(":8080")
}
运行程序
go run main.go
image
浏览器运行:
image
生成JSON
func AsciiJSON() {
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{
"name": "叫我詹躲躲",
"gend": "男",
})
})
r.Run(":8080")
}
调用
package main
import (
"app/function"
"github.com/gin-gonic/gin"
)
func main() {
//使用AsciiJSON生成带有转义的非ASCII字符的纯ASCII JSON。
function.AsciiJSON()
}
image
测试get请求
绑定表单数据请求与自定义结构
//绑定表单数据请求与自定义结构
type StructA struct {
FieldA string `form:"field_a"`
}
type StructB struct {
NestedStruct StructA
FieldB string `form:"field_b"`
}
//get请求
func GetFormData(c *gin.Context) {
var b StructB
c.Bind(&b)
c.JSON(200, gin.H{
"a": b.NestedStruct,
"b": b.FieldB,
})
}
调用
package main
import (
"app/function"
"github.com/gin-gonic/gin"
)
func main() {
//将表单数据请求与自定义结构绑定
r := gin.Default()
//测试get请求
r.GET("/getFormData", function.GetFormData)
r.Run()
}
image
查询返回信息
//绑定查询字符串或发布数据
type PersonInfo struct {
Name string `form:"name"`
Address string `form:"address"`
Memo string `form:"memo"`
}
//返回信息
func QueryInfo(c *gin.Context) {
var person PersonInfo
if c.ShouldBind(&person) == nil {
log.Println(person.Name)
log.Println(person.Address)
log.Println(person.Memo)
}
c.String(200, "Success")
}
调用
package main
import (
"app/function"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
//查询返回信息
r.GET("/queryInfo", function.QueryInfo)
r.Run()
}
image
自定义HTTP配置
http.ListenAndServe(":8080", router)
或者
s := &http.Server{
Addr: ":8080",
Handler: router,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
s.ListenAndServe()
自定义日志文件
router := gin.New()
router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",
param.ClientIP,
param.TimeStamp.Format(time.RFC1123),
param.Method,
param.Path,
param.Request.Proto,
param.StatusCode,
param.Latency,
param.Request.UserAgent(),
param.ErrorMessage,
)
}))
router.Use(gin.Recovery())
router.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
router.Run(":8080
参考文档
1.解决GO语言安装air框架时遇到go: inconsistent vendoring问题
2.Glide cannot find package “.” in
3.warning: GOPATH set to GOROOT (/usr/local/go) has no effect
4.gin官方文档
5.Gin框架中文文档
6.Go 不同文件之间的引用
有疑问加站长微信联系(非本文作者)