GO随笔-表单输入

栏目: Go · 发布时间: 5年前

内容简介:对于表单form都不陌生,GO是如何处理表单的呢?先写个例子:文件命名为

表单的处理

对于表单form都不陌生,GO是如何处理表单的呢?

先写个例子:

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

文件命名为 login.gtpl (与html无异)

紧接着,需要有http服务

package main

import (
    "fmt"
    "html/template"
    "log"
    "net/http"
    "strings"
)

func login(w http.ResponseWriter, r *http.Request) {
    fmt.Println("method:", r.Method) //获取请求的方法
    if r.Method == "GET" {
        t, _ := template.ParseFiles("login.gtpl")
        t.Execute(w, nil)
    } else {
        r.ParseForm()
        //请求的是登陆数据,那么执行登陆的逻辑判断
        fmt.Println("username:", r.Form["username"])
        fmt.Println("password:", r.Form["password"])
    }
}

func main() {
    http.HandleFunc("/login", login)         //设置访问的路由
    err := http.ListenAndServe(":9090", nil) //设置监听的端口
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

这就写好了一个能够完成登陆操作的功能。

用户访问 http://domain:9090/login 即可看到登陆界面。紧接着输入用户名和密码即可完成登陆。

中间都发生了什么事情呢?

  • 服务端绑定“/login”在Handle(login)上。
  • 服务端监听9090端口。
  • 用户访问服务端的9090端口。并且url是“/login”
  • 服务端接收到请求,解析路由后,将该请求分配给Handle(login),进入登陆逻辑。

这就是请求的过程。之后是响应过程

  • 通过 r.Method 拿到请求的方法
  • 判断请求的方法,若是get,则渲染模板 template.ParseFiles("login.gtpl") 。并且将模板响应(w) t.Execute(w, nil) 给客户端,浏览器上显示登陆界面。
  • 当用户填写完信息点击登陆按钮时,将表单信息以post方法请求url action="/login"
  • 再次重复以上逻辑,判断方法为post时执行解析表单操作。 r.ParseForm() 并且将相关信息打印出来。
这里需要注意的一点是。Handler是不会自动解析表单的,需要显示的调用 r.ParseForm() 。才能对表单执行操作 r.Form["username"]

request.Form 是一个 url.Values 类型,里面存储的是对应的类似 key=value 的信息

另外 Request 本身提供了 FormValue() 来获取用户提供的参数。如 r.Form["username"] 也可写成 r.FormValue("username") 。调用 r.FormValue 时会自动调用 r.ParseForm ,所以不必提前调用。


以上所述就是小编给大家介绍的《GO随笔-表单输入》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Thirty-three Miniatures

Thirty-three Miniatures

Jiří Matoušek / American Mathematical Socity / 2010-6-18 / USD 24.60

This volume contains a collection of clever mathematical applications of linear algebra, mainly in combinatorics, geometry, and algorithms. Each chapter covers a single main result with motivation and......一起来看看 《Thirty-three Miniatures》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试