第15章 15.5-健壮的http应用

2020-01-25  本文已影响0人  yezide
package main

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

const form = `<html><body><form action="#" method="post" name="bar">
        <input type="text" name="in"/>
        <input type="submit" value="Submit"/>
    </form></html></body>`

type MyHandleFunc func(http.ResponseWriter, *http.Request)

// 最简单的输出html
func SimpleServer(w http.ResponseWriter, req *http.Request) {
    io.WriteString(w, "<h1>hello go</h1>")
}

// 首先是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)
        }
}
上一篇下一篇

猜你喜欢

热点阅读