从0开始学go第七天

gin获取表单from中的数据

模拟简单登录页面:

从0开始学go第七天_第1张图片





    

    login



    
    
//当submit被点击以后,会向服务端发送请求,发送方式为post

对于POST的返回页面:

从0开始学go第七天_第2张图片





    

    index



    

Hello , {{ .Name }}!

你的密码是 : {{ .Password }}

获取方法一代码:

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")
}

你可能感兴趣的:(golang,开发语言,后端)