美文网首页
第15章 15.5-健壮的http应用

第15章 15.5-健壮的http应用

作者: yezide | 来源:发表于2020-01-25 14:57 被阅读0次
    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)
            }
    }
    

    相关文章

      网友评论

          本文标题:第15章 15.5-健壮的http应用

          本文链接:https://www.haomeiwen.com/subject/qmjrthtx.html