package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
type LoginForm struct {
User string `form:"user" binding:"required"`
Password string `form:"password" binding:"required"`
}
func main() {
r := gin.Default()
r.MaxMultipartMemory = 8 << 20 //8M
//r.LoadHTMLGlob("templates/*")
r.POST("/login", logInHandler)
r.POST("/form-post", formPostHandler)
r.GET("/someJson", someJson)
r.GET("/index", userIndex)
r.GET("/pure-json", pureJsonHandler)
r.GET("/json", JsonHandler)
r.POST("/post", postHandler)
r.GET("secure-json", securejsonHandler)
r.POST("/upload", uploadHandler)
r.POST("/uploads", uploadsHandler)
r.GET("/someDataFromReader", dataHeadler)
r.Run()
}
func dataHeadler(c *gin.Context) {
get, err := http.Get("https://www.baidu.com")
if err != nil || get.StatusCode != http.StatusOK {
c.Status(http.StatusBadRequest)
return
}
reader := get.Body
contentLength := get.ContentLength
contentType := get.Header.Get("Content-Type")
extraheaders := map[string]string{
"Content-Disposition": `attachment; filename="gopher.png"`,
}
c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraheaders)
}
func uploadsHandler(c *gin.Context) {
}
func uploadHandler(c *gin.Context) {
file, _ := c.FormFile("file") //这里说明一下.在进行文件上传的时候,
// 文件类型要选择file类型,.文件参数要与这的参数一直才可以被识别.产上传能成功.否则就会报错
fmt.Println(file.Filename)
dst := "./" + file.Filename
err := c.SaveUploadedFile(file, dst)
if err != nil {
fmt.Println(err)
return
}
c.JSON(http.StatusOK, gin.H{
"msg": "ok",
})
}
func securejsonHandler(c *gin.Context) {
name := []string{"lean", "austin", "foo"}
name1 := map[string]string{"name": "mingzi", "mingzi": "name"}
c.SecureJSON(http.StatusOK, name)
c.SecureJSON(http.StatusOK, name1)
}
func postHandler(c *gin.Context) {
id := c.Query("id")
page := c.DefaultQuery("page", "0")
name := c.PostForm("name")
message := c.PostForm("message")
fmt.Printf("id: %s,page: %s,name:%s,message:%s", id, page, name, message)
}
func pureJsonHandler(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"html": "<b>Hello, world!</b>",
})
}
func JsonHandler(c *gin.Context) {
c.PureJSON(http.StatusOK, gin.H{
"html": "<b>Hello, world!</b>",
})
}
func formPostHandler(c *gin.Context) {
form := c.PostForm("message")
nick := c.DefaultPostForm("nick", "anonymous")
c.JSON(http.StatusOK, gin.H{
"status": "posted",
"message": form,
"nick": nick,
})
}
func someJson(c *gin.Context) {
m := map[string]interface{}{
"lang": "go语言",
"tag": "<br>",
}
c.AsciiJSON(http.StatusOK, m)
}
func userIndex(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", gin.H{
"title": "我就是title",
})
}
func logInHandler(c *gin.Context) {
var form LoginForm
err := c.ShouldBind(&form)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{
"status": "unauthorized",
})
} else {
c.JSON(http.StatusOK, gin.H{
"status": "you are logged in",
})
}
}
12-18
3284
3284
07-13
1850
1850
07-13
774
774

被折叠的 条评论
为什么被折叠?



