go语言form表单提交以及后台如何接收并返回做一个简单的解释

我们大部分情况下都离不开form表单的提交,今天就来介绍一下form表单的提交,以及后台的返回
先给大家看效果
这里写图片描述
点击登录以后出现的效果
这里写图片描述
这是本地测试的效果
接下来就上代码了
前端代码

<html>
<head><title></title></head>
<body>
    <form action="http://localhost:9090/" method="post">
        用户名:<input type="text" name="username">
        密  码:<input type="text" name="password">
        <input type="submit" value="登录">
    </form>
</body>
</html>

后端代码

package main
import (
    "fmt"
    "html/template"
    "log"
    "net/http"
    "strings"
)
func sayHelloName(w http.ResponseWriter, r *http.Request) {
    // 解析url传递的参数
    r.ParseForm()
    for k, v := range r.Form {
        fmt.Println("key:", k)
        // join() 方法用于把数组中的所有元素放入一个字符串。
        // 元素是通过指定的分隔符进行分隔的
        fmt.Println("val:", strings.Join(v, ""))
    }
    // 输出到客户端
    name :=r.Form["username"]
    pass :=r.Form["password"]
    for i,v :=range name{
        fmt.Println(i)
        fmt.Fprintf(w,"用户名:%v\n",v)
    }
    for k,n :=range pass{
        fmt.Println(k)
        fmt.Fprintf(w,"密码:%v\n",n)
    }
}
func login(w http.ResponseWriter, r *http.Request) {
    fmt.Println("method:", r.Method)
    if r.Method == "GET" {
        t, _ := template.ParseFiles("login.html")
        // func (t *Template) Execute(wr io.Writer, data interface{}) error {
        t.Execute(w, nil)
    } else {
        r.ParseForm()
        fmt.Println("username:", r.Form["username"])
        fmt.Println("password:", r.Form["password"])
    }
}
func main() {
    http.HandleFunc("/", sayHelloName)
    http.HandleFunc("/login", login)
    err := http.ListenAndServe(":9090", nil)
    if err != nil {
        log.Fatal("ListenAndserve:", err)
    }
}

好了,这个只是简单的form表单的提交和返回,下一篇会讲到如何将form表单提交的数据和数据库进行匹配,来达到登录或注册的目的,好了,就到这里了,如果有什么疑问可以在下方评论或留言!

猜你喜欢

转载自blog.csdn.net/qq_35730500/article/details/54584835