包括获取参数,组装参数,文件的上传和下载
package ginstudy
import (
"fmt"
"github.com/gin-gonic/gin"
"log"
"net/http"
)
//第一个Gin程序
func GinHello(c *gin.Context) {
c.JSON(200, gin.H{"message": "pong"})
}
// get方法获取参数并输出
func GetParam(c *gin.Context) {
//获取请求的全路径
fmt.Println(c.FullPath())
name := c.DefaultQuery("name", "")
c.Writer.WriteString("获取到的参数是" + name)
}
// post方法获取参数并输出
func PostParam(c *gin.Context) {
userName := c.PostForm("username")
password := c.PostForm("password")
c.Writer.WriteString("userName:" + userName + " password:" + password)
}
//使用GetPostForm获取参数
func GetPostParam(c *gin.Context) {
userName, exist := c.GetPostForm("username")
if !exist {
c.Writer.WriteString("userName参数不存在")
}
password, exist := c.GetPostForm("password")
if !exist {
c.Writer.WriteString("password参数不存在")
}
c.Writer.WriteString("userName:" + userName + " password:" + password)
}
//Restful风格请求参数,删除动作
func Delete(c *gin.Context) {
userId := c.Param("userId")
c.Writer.WriteString("Restful接口获取到的userId是:" + userId)
}
/**
使用对象(结构体)接收参数
*********************************************************************************
*/
//定义一个接收参数的结构体
type User struct {
Name string `form:"name" binding:"required"`
Age int32 `form:"age" binding:"required"`
Phone string `form:"phone"`
}
//get请求,请求参数组装为User对象
func GetParamUseStruct(c *gin.Context) {
var user User
err := c.ShouldBindQuery(&user)
if err != nil {
panic(err.Error())
}
c.JSON(200, gin.H{"user": user})
}
//post请求,请求参数组装为User对象
func PostParamUseStruct(c *gin.Context) {
var user User
if err := c.ShouldBind(&user); err != nil {
log.Fatal(err.Error())
}
c.JSON(200, gin.H{"user": user})
}
//post请求,请求参数组装为User对象,请求参数是Json
func PostParamUseStructWithJson(c *gin.Context) {
var user User
if err := c.ShouldBindJSON(&user); err != nil {
log.Fatal(err.Error())
}
c.JSON(200, gin.H{"user": user})
}
//结构体以json形式返回给浏览器
func WriteJsonUseStruct(c *gin.Context) {
var user User = User{Name: "贾宝玉", Age: 18, Phone: "1313133"}
c.JSON(200, &user)
}
//上传单个文件
func UploadFile(c *gin.Context) {
file, err := c.FormFile("file")
if err != nil {
panic(err.Error())
}
//SaveUploadedFile的最后一个参数是文件名,而非目录
err = c.SaveUploadedFile(file, "/Users/jliangzhang/Documents/new.png")
if err != nil {
panic(err.Error())
}
c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
}
//上传多个文件
func UploadFiles(c *gin.Context) {
form, _ := c.MultipartForm()
files := form.File["files"]
for _, file := range files {
//file.Filename
fmt.Printf(file.Filename)
err := c.SaveUploadedFile(file, "/Users/jliangzhang/Documents/"+"新文件"+file.Filename)
if err != nil {
panic(err.Error())
}
c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
}
}
//文件下载:将接受的参数组装成文本文件
func DownLoadTextFile(c *gin.Context) {
/* c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
c.Writer.Header().Add("Content-Type", "application/octet-stream")
c.File("./file/a.txt")*/
content := c.Query("content")
content = "hello" + content
c.Writer.WriteHeader(http.StatusOK)
c.Header("Content-Disposition", "attachment; filename=hello.txt")
c.Header("Content-Type", "application/text/plain")
c.Header("Accept-Length", fmt.Sprintf("%d", len(content)))
c.Writer.Write([]byte(content))
}
//文件下载:任意类型的文件下载
func DownLoadUsualFile(c *gin.Context) {
c.Writer.Header().Add("Content-Disposition", "attachment; filename=hello.sql")
c.Writer.Header().Add("Content-Type", "application/octet-stream")
//如果该文件不存在,该方法也不会报错,需要注意
c.File("/Users/jliangzhang/Documents/test.sql")
}
func GinTest() {
router := gin.Default()
router.GET("/first/gin", ginstudy.GinHello)
router.GET("/getParam", ginstudy.GetParam)
router.POST("/postParam", ginstudy.PostParam)
router.POST("/getPostParam", ginstudy.GetPostParam)
router.DELETE("/delete/:userId", ginstudy.Delete)
router.GET("/getParam/user", ginstudy.GetParamUseStruct)
router.POST("/postParam/user", ginstudy.PostParamUseStruct)
router.POST("/postParam/user/json", ginstudy.PostParamUseStructWithJson)
router.GET("/response/json", ginstudy.WriteJsonUseStruct)
router.POST("/upload/file", ginstudy.UploadFile)
router.POST("/upload/files", ginstudy.UploadFiles)
router.GET("/download/text/file", ginstudy.DownLoadTextFile)
router.GET("/download/usual/file", ginstudy.DownLoadUsualFile)
router.Run("0.0.0.0:8080")
}