学习思维导图
提高篇
多形式渲染
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main(){
r := gin.Default()
//静态资源映射
r.Static("/static","./static")
//静态资源文件路径
r.LoadHTMLGlob("templates/**/*")
"""
-------------------------------------------------------------------------------
渲染JSON数据
-------------------------------------------------------------------------------
"""
r.GET("/getJson", func(c *gin.Context) {
var type User struct {
Name string `json:"name"` //如果后面加上`json:user`那么Name就会变成user
Password string `json:"password"`
}
User.Name = "Golang1"
User.Password = "123"
c.JSON(http.StatusOK,User)
})
"""
-------------------------------------------------------------------------------
渲染XML数据
-------------------------------------------------------------------------------
"""
r.GET("/getXML", func(c *gin.Context) {
user := &User{
Name: "Golang2",
Password: "456",
}
c.XML(http.StatusOK,user)
})
"""
-------------------------------------------------------------------------------
渲染HTML模板数据
-------------------------------------------------------------------------------
"""
r.GET("/postHTML", func(c *gin.Context) {
c.HTML(http.StatusOK,"learn.html",gin.H{
"title":"learning Golang",
})
})
r.GET("/getHTML", func(c *gin.Context) {
c.HTML(http.StatusOK,"read.html",gin.H{
"title":"Reading Golang",
})
})
"""
-------------------------------------------------------------------------------
渲染YMAL模板数据
-------------------------------------------------------------------------------
"""
r.GET("/getYAML", func(c *gin.Context) {
c.YAML(http.StatusOK, gin.H{
"message": "Hello Golang",
"status": http.StatusOK
})
})
"""
-------------------------------------------------------------------------------
渲染ProtoBuf模板数据
-------------------------------------------------------------------------------
"""
r.GET("/getProtoBuf", func(c *gin.Context) {
reps := []int64{int64(1), int64(2)}
label := "test"
//数据在响应中变为二进制数据
data := &protoexample.Test{
Label: &label,
Reps: reps,
}
// 输出被序列化了的数据
c.ProtoBuf(http.StatusOK, data)
})
}
文件服务器
package main
import "github.com/gin-gonic/gin"
func main() {
r:=gin.Default()
r.GET("/file",fileServer)
r.Run()
}
func fileServer(c *gin.Context) {
//文件的路径
path:="D:/Golang/Gin/path/"
fileName:=path+c.Query("name")
c.File(fileName)
单文件上传
index.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>上传文件示例</title>
</head>
<body>
<form action="/uploadfiles" method="post" enctype="multipart/form-data">
<input type="file" name="f1">
<input type="submit" value="上传">
</form>
</body>
</html>
单文件上传
func main() {
r := gin.Default()
r.LoadHTMLGlob("views/index.html")
r.GET("/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", nil)
})
r.POST("/uploadfile", func(c *gin.Context) {
//获取表单数据 参数为name值
f, err := c.FormFile("f1")
//错误处理
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err,
})
return
} else {
//将文件保存至本项目根目录中
c.SaveUploadedFile(f, f.Filename)
//保存成功返回正确的Json数据
c.JSON(http.StatusOK, gin.H{
"message": "OK",
})
}
})
r.Run()
}
多文件上传
index.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>上传文件示例</title>
</head>
<body>
<form action="/uploadfiles" method="post" enctype="multipart/form-data">
<input type="file" name="f1s">
<input type="file" name="f1s">
<input type="submit" value="上传">
</form>
</body>
</html>
多文件上传
func main() {
r:=gin.Default()
r.LoadHTMLGlob("views/index.html")
r.MaxMultipartMemory = 8 << 20 // 8 MiB 设置最大的上传文件的大小
r.GET("/index", func(c *gin.Context) {
c.HTML(http.StatusOK,"index.html",nil)
})
r.POST("/uploadfiles", func(c *gin.Context) {
form,err:=c.MultipartForm()
files:=form.File["f1s"]
//错误处理
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err,
})
return
}
for _,f:=range files{
fmt.Println(f.Filename)
c.SaveUploadedFile(f,f.Filename)
}
c.JSON(http.StatusOK, gin.H{
"message": "OK",
})
})
r.Run()
}
文件下载
func downloadFile(fileFullPath string, res *restful.Response) {
file, err := os.Open(fileFullPath)
if err != nil {
res.WriteEntity(_dto.ErrorDto{Err: err})
return
}
defer file.Close()
fileName := path.Base(fileFullPath)
fileName = url.QueryEscape(fileName) // 防止中文乱码
res.AddHeader("Content-Type", "application/octet-stream")
res.AddHeader("content-disposition", "attachment; filename=\""+fileName+"\"")
_, error := io.Copy(res.ResponseWriter, file)
if error != nil {
res.WriteErrorString(http.StatusInternalServerError, err.Error())
return
}
}
后记
喜欢的话可以三连,后续继续更新其他内容,帮忙推一推,感谢观看!