go的net/http的http-form
go http-form 表格获取数据
package main
import (
"fmt"
"io"
"net/http"
)
var form string = `<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="#" method="post" name="bar">
<input type="text" name="in" />
<input type="text" name="in" />
<input type="submit" value="Submit" />
</form>
</body>
</html>`
func SimpleServer(w http.ResponseWriter, request *http.Request) {
io.WriteString(w, "<h1>Hello, world.</h1>")
}
func FormServer(w http.ResponseWriter, request *http.Request) {
w.Header().Set("Content-Type", "text/html")
switch request.Method {
case "GET":
io.WriteString(w, form)
case "POST":
request.ParseForm()
io.WriteString(w, "request.Form[in][0] :\n")
io.WriteString(w, request.Form["in"][0])
io.WriteString(w, "\t")
io.WriteString(w, "request.Form[in][1] :\n")
io.WriteString(w, request.Form["in"][1])
io.WriteString(w, "\t\n")
// request.FormValue("in") 只能取到第一个值,request.Form["in"]取到数组
io.WriteString(w, request.FormValue("in"))
io.WriteString(w, "\t")
fmt.Printf("request.Form[in]= %v,%T \n",request.Form["in"],request.Form["in"])
fmt.Printf("request.FormValue(\"in\")= %v,%T \n",request.FormValue("in"),request.FormValue("in"))
}
}
func main() {
http.HandleFunc("/test1", SimpleServer)
http.HandleFunc("/test2", FormServer)
if err := http.ListenAndServe(":8888", nil); err != nil {
}
}
go http 增加pannic判断
package main
import (
"fmt"
"io"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", LogPanic(test))
http.HandleFunc("/form", LogPanic(form))
err := http.ListenAndServe(":9000", nil)
if err != nil {
fmt.Println("服务开启失败", err)
return
}
}
func test(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "hello")
panic("test")
}
func form(w http.ResponseWriter, request *http.Request) {
var fromTable string = `<html><head></head><body>
<form method="post" action="">
<input type="text" name="test" />
<input type="text" name="test" />
<input type="submit" name="提交" />
</from>
</body></html>`
w.Header().Set("Content-Type", "text/html")
switch request.Method {
case "GET":
io.WriteString(w, fromTable)
case "POST":
request.ParseForm()
io.WriteString(w, request.Form["test"][1])
io.WriteString(w, "\n")
io.WriteString(w, request.FormValue("test"))
}
}
func LogPanic(handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer func() {
if x := recover(); x != nil {
log.Printf("%v panic:%v", r.RemoteAddr, x)
}
}()
handler(w, r)
}
}
写入自己的博客中才能记得长久