1.首先在linux环境上安装go环境,这个网上搜搜就行
2.初始化一个go mod,网上搜搜怎么初始化
3.下面go代码的网址和端口绑定自己本机的就行
4.与另一篇CSDN一起食用,效果更好哟--->?libcurl的get、post的使用-CSDN博客
package main
import (
"github.com/gin-gonic/gin"
"flag"
"fmt"
)
func downFile(c *gin.Context, filePath string, filename string) {
c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
c.Writer.Header().Add("Content-Type", "application/octet-stream")
fmt.Println(filePath)
c.File(filePath)
}
// go build -o go_gin main.go
func main() {
var downPath *string = flag.String("down", "/tmp", "the down dir")
flag.Parse()
fmt.Printf("downPath = %s\n", *downPath)
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "Hello World!",
})
})
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.POST("/submit", func(c *gin.Context) {
var json struct {
Name string `json:"name"`
Email string `json:"email"`
}
if err := c.Bind(&json); err == nil {
print("name = " + json.Name)
print("email = " + json.Email)
c.JSON(200, gin.H{
"message": "JSON received",
"name": json.Name,
"email": json.Email,
})
} else {
c.JSON(400, gin.H{"error": err.Error()})
}
})
// 文件下载
r.POST("/down_file", func(c *gin.Context) {
var json struct {
FileName string `json:"file_name"`
}
if err := c.Bind(&json); err == nil {
filePath := (*downPath) + "/" + json.FileName
downFile(c, filePath, json.FileName)
}
})
r.Run("10.74.37.146:9999") // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}