1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| package main
import ( "io" "log" "net/http" )
const form = ` <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> <title>产品添加-产品管理系统</title> </head> <body> <h3>产品管理表单</h3> <form action="#" method="post"> 图书名称:<input type='text' name='title' /> <hr /> 销售价格:<input type="text" name='price' /> <hr /> 市场价格:<input type="text" name='market_price' /> <hr /> <input type="submit" name="submit" value="添加" /> <input type="reset" name="reset" value="重置" /> </form> </body> </html> `
func formServer(writer http.ResponseWriter, request *http.Request) { writer.Header().Set("Content-Type", "text/html") switch request.Method { case "GET": _, _ = io.WriteString(writer, form) case "POST": _ = request.ParseForm() _, _ = io.WriteString(writer, "title = ") _, _ = io.WriteString(writer, request.Form["title"][0]+"\n") _, _ = io.WriteString(writer, "price = ") _, _ = io.WriteString(writer, request.Form["price"][0]+"\n") _, _ = io.WriteString(writer, "market_price = ") _, _ = io.WriteString(writer, request.Form["market_price"][0]+"\n") } }
func simpleServer(writer http.ResponseWriter, request *http.Request) { _, _ = io.WriteString(writer, "<h1>Hello ! This is test1") panic("This is a panic test !") } func logPanics(handle http.HandlerFunc) http.HandlerFunc { return func(writer http.ResponseWriter, request *http.Request) { defer func() { if x := recover(); x!=nil{ log.Printf("[%v] caught panic: %v",request.RemoteAddr, x) } }() handle(writer, request) } } func main() { http.HandleFunc("/test1", logPanics(simpleServer)) http.HandleFunc("/test2", logPanics(formServer)) if err := http.ListenAndServe("0.0.0.0:8880", nil); err != nil {
} }
|