当前位置:首页 > 编程笔记 > 正文
已解决

从0开始学go第七天

来自网友在路上 176876提问 提问时间:2023-10-12 09:56:57阅读次数: 76

最佳答案 问答题库768位专家为你答疑解惑

gin获取表单from中的数据

模拟简单登录页面:

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><title>login</title>
</head><body><form action="/login" method="post"><div><label for="username">username:</label><input type="text" name="username" id="username"></div><div><label for="password">password:</label><input type="text" name="password" id="password"></div><div>//当submit被点击以后,会向服务端发送请求,发送方式为post<input type="submit" value="登录"></div></form></body></html>

对于POST的返回页面:

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><title>index</title>
</head><body><h1>Hello , {{ .Name }}!</h1><h1>你的密码是 : {{ .Password }}</h1></body></html>

获取方法一代码:

package main//from表单提交的参数
import ("net/http""github.com/gin-gonic/gin"
)func main() {r := gin.Default()r.LoadHTMLFiles("./login.html", "./index.html")r.GET("/login", func(c *gin.Context) {c.HTML(http.StatusOK, "login.html", nil)})//POST请求r.POST("/login", func(c *gin.Context) {username := c.PostForm("username")password := c.PostForm("password")c.HTML(http.StatusOK, "index.html", gin.H{"Name":     username,"Password": password,})})r.Run(":9090")
}

获取方法二代码:

带默认值

package main//from表单提交的参数
import ("net/http""github.com/gin-gonic/gin"
)func main() {r := gin.Default()r.LoadHTMLFiles("./login.html", "./index.html")r.GET("/login", func(c *gin.Context) {c.HTML(http.StatusOK, "login.html", nil)})//POST请求r.POST("/login", func(c *gin.Context) {// 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(":9090")
}

方法三:GetPostFrom

package main//from表单提交的参数
import ("net/http""github.com/gin-gonic/gin"
)func main() {r := gin.Default()r.LoadHTMLFiles("./login.html", "./index.html")r.GET("/login", func(c *gin.Context) {c.HTML(http.StatusOK, "login.html", nil)})//POST请求r.POST("/login", func(c *gin.Context) {// username := c.PostForm("username")// password := c.PostForm("password")//username := c.DefaultPostForm("username", "somebody")//password := c.DefaultPostForm("password", "*******")username,ok := c.GetPostForm("username")if !ok {username = "sb"}password,ok := c.GetPostForm("password")if !ok {password = "******"}c.HTML(http.StatusOK, "index.html", gin.H{"Name":     username,"Password": password,})})r.Run(":9090")
}

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"从0开始学go第七天":http://eshow365.cn/6-19154-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!