go語言實現(xiàn)處理表單輸入
更新時間:2015年03月20日 10:44:28 投稿:hebedich
本文給大家分享的是一個使用go語言實現(xiàn)處理表單輸入的實例代碼,非常的簡單,僅僅是實現(xiàn)了用戶名密碼的驗證,有需要的小伙伴可以自由擴展下。
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傳遞的參數(shù)
r.ParseForm()
//在服務(wù)端打印信息
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() 方法用于把數(shù)組中的所有元素放入一個字符串。
// 元素是通過指定的分隔符進行分隔的
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")
// 執(zhí)行解析模板
// 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() {
//設(shè)置訪問路由
http.HandleFunc("/", sayHelloName)
http.HandleFunc("/login", login)
//設(shè)置監(jiān)聽端口
err := http.ListenAndServe(":9090", nil)
if err != nil {
log.Fatal("ListenAndserve:", err)
}
}
以上所述就是本文的全部內(nèi)容了,希望大家能夠喜歡。
相關(guān)文章
Golang常用環(huán)境變量說明與設(shè)置詳解
這篇文章主要介紹了Golang常用環(huán)境變量說明與設(shè)置,需要的朋友可以參考下2020-02-02Linux系統(tǒng)下Go語言開發(fā)環(huán)境搭建
這篇文章主要介紹了Linux系統(tǒng)下Go開發(fā)環(huán)境搭建,需要的朋友可以參考下2022-04-04GoLang中的互斥鎖Mutex和讀寫鎖RWMutex使用教程
RWMutex是一個讀/寫互斥鎖,在某一時刻只能由任意數(shù)量的reader持有或者一個writer持有。也就是說,要么放行任意數(shù)量的reader,多個reader可以并行讀;要么放行一個writer,多個writer需要串行寫2023-01-01golang對etcd存取和數(shù)值監(jiān)測的實現(xiàn)
這篇文章主要介紹了golang對etcd存取和數(shù)值監(jiān)測的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-09-09golang操作elasticsearch的實現(xiàn)
這篇文章主要介紹了golang操作elasticsearch,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-06-06