第15章 15.5-健壮的http应用

package main

import (
    "io"
    "log"
    "net/http"
)

const form = `
` type MyHandleFunc func(http.ResponseWriter, *http.Request) // 最简单的输出html func SimpleServer(w http.ResponseWriter, req *http.Request) { io.WriteString(w, "

hello go

") } // 首先是GET方式,显示html表单 // 点submit之后变成了post // 然后读取form的in字段,就是input框的值显示出来 func FormServer(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-type", "text/html") switch req.Method { case "GET": io.WriteString(w, form) case "POST": io.WriteString(w, req.FormValue("in")) } } func LogPanic(f MyHandleFunc) MyHandleFunc { return func(w http.ResponseWriter, req *http.Request) { defer func() { if x := recover(); x != nil { log.Printf("[%v] caught panic: %v", req.RemoteAddr, x) } }() f(w, req) } } func main() { http.HandleFunc("/simple1", LogPanic(SimpleServer)) http.HandleFunc("/simple2", LogPanic(FormServer)) if err := http.ListenAndServe(":8081", nil) ; err != nil { panic(err) } }

你可能感兴趣的:(第15章 15.5-健壮的http应用)