go系列之利用Gin框架获取form参数
生活随笔
收集整理的這篇文章主要介紹了
go系列之利用Gin框架获取form参数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
利用Gin框架獲取form參數
除了通過URL查詢參數提交數據到服務器外,常用的還有通過Form表單的方式。Form表單相比URL查詢參數,用戶體驗好,可以承載更多的數據,尤其是文件上傳,所以也更為方便。Form 表單對于Form表單,我們不會陌生,比如input文本框、密碼框等等,可以讓我們輸入一些數據,然后點擊「保存」、「提交」等按鈕,把數據提交到服務器的。對于Form表單來說,有兩種提交方式GET和POST。其中GET方式就是我們前兩篇文章的URL查詢參數的方式,參考即可獲得對應的參數鍵值對,這篇文章主要介紹POST的方式的表單,而Gin處理的也是這種表單。
主函數:
package mainimport ("github.com/gin-gonic/gin""net/http" )func main() {//Default返回一個默認的路由引擎r := gin.Default()r.LoadHTMLFiles("./login.html","./index.html")r.GET("/login", func(c *gin.Context) {c.HTML(http.StatusOK,"login.html",nil)})//login postr.POST("/login", func(c *gin.Context) {//獲取Form表單提交的數據//username:=c.PostForm("username")//password:=c.PostForm("password")username:= c.DefaultPostForm("username","somebody")password:=c.DefaultPostForm("password","***")//改為頁面中沒有定義的,則會返回***c.HTML(http.StatusOK,"index.html",gin.H{"Name": username,"Password":password,})})r.Run(":8080") }login頁面
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>login</title> </head> <body> <form action="/login" method="post" navalidate autocomplete="off" u><div><label for="username"> username:</label><input type="text" name="username" id="username"></div><div><label for="password"> password:</label><input type="password" name="password" id="password"></div><div><input type="submit" value="登陸"></div> </form> </body> </html>index頁面
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>index</title> </head> <body> <h1> hello {{.Name}}!</h1> <p>你的密碼是{{.Password}}</p> </body> </html>沒有定義時訪問http://localhost:8080/login
正確定義后:
取不到的時候。注意觀察細節
總結
以上是生活随笔為你收集整理的go系列之利用Gin框架获取form参数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 实习第一周(Golang)
- 下一篇: flutter利用高德如何获取地理位置信