表单提交
package main
import (
"fmt"
"html/template" //支持模板html
"log" //打印日志log类
"net/http"
"strings"
)
func sayHelloName(w http.ResponseWriter, r *http.Request) {
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)
fmt.Println("val:", strings.Join(v, ""))
}
fmt.Fprintf(w, "hello box")
}
func login(w http.ResponseWriter, r *http.Request) {
//打印请求的方法
fmt.Println("method", r.Method)
if r.Method == "GET" { //如果请求方法为get显示login.html,并相应给前端
t, _ := template.ParseFiles("login.html")
t.Execute(w, nil)
} else {
//否则走打印输出post接受的参数username和password
fmt.Println(r.PostFormValue("username"))
fmt.Println(r.PostFormValue("password"))
}
}
func main() {
//监听 / 走sayHelloName
http.HandleFunc("/", sayHelloName)
//路由控制/login 走login方法
http.HandleFunc("/login", login)
err := http.ListenAndServe(":8081", nil)
if err != nil {
log.Fatal("ListenAndServe:", err)
}
}
<form method="POST" action="/login">
<input type="text" name="username" />
<input type="text" name="password" />
<input type="submit" value="登录" />
</form>
表单验证
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"regexp"
"strconv"
)
func sayHelloName(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello box")
}
func login(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
t, _ := template.ParseFiles("login.html")
t.Execute(w, nil)
} else if r.Method == "POST" {
username := r.FormValue("username")
password := r.FormValue("password")
phone := r.FormValue("phone")
like := r.FormValue("like")
sex := r.FormValue("sex")
utype := r.FormValue("utype")
fmt.Println(like)
fmt.Println(sex)
fmt.Println(utype)
//获取年龄之后转成int型
age, err := strconv.Atoi(r.FormValue("age"))
if err != nil {
w.Write([]byte("数字转化出错了,那么可能就不是数字"))
return
}
if username == "" || password == "" || age == 0 {
w.Write([]byte("username and password and age must not null"))
return
}
//获取数据判定大小
if age > 100 {
w.Write([]byte("age is to big"))
return
}
if m, _ := regexp.MatchString(`^(1[3|4|5|8][0-9]\d{4,8})$`, phone); !m {
w.Write([]byte("phone is error"))
return
}
} else {
fmt.Println("error")
}
}
func main() {
http.HandleFunc("/", sayHelloName)
http.HandleFunc("/login", login)
err := http.ListenAndServe(":8081", nil)
if err != nil {
log.Fatal("ListenAndServe:", err)
}
}