温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

go语言实现处理表单输入

发布时间:2020-08-28 13:51:11 来源:脚本之家 阅读:129 作者:hebedich 栏目:编程语言

login.html

复制代码 代码如下:

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

main.go

复制代码 代码如下:

package main
import (
    "fmt"
    "html/template"
    "log"
    "net/http"
    "strings"
)
func sayHelloName(w http.ResponseWriter, r *http.Request) {
    // 解析url传递的参数
    r.ParseForm()
    //在服务端打印信息
    fmt.Println(r.Form)
    fmt.Println("path", r.URL.Path)
    fmt.Println("Scheme", r.URL.Scheme)
    fmt.Println(r.Form["url_long"])
    for k, v := range r.Form {
        fmt.Println("key:", k)
        // join() 方法用于把数组中的所有元素放入一个字符串。
        // 元素是通过指定的分隔符进行分隔的
        fmt.Println("val:", strings.Join(v, ""))
    }
    // 输出到客户端
    fmt.Fprintf(w, "hello astaxie!")
}
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)
    }
}

以上所述就是本文的全部内容了,希望大家能够喜欢。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI