go http simple form processing

// form processing
package main

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

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

func deal2 (w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/html")

    Http // Method behalf of the specified method
    switch r.Method {
        case "GET":
            //io.WriteString(w, s string) writes the string s in w
            io.WriteString(w, form)
        case "POST":
            //func (*Request) PostFormValue
            // PostFormValue return key field to obtain a bond r.PostForm query results [] value of a first slice of the string
            io.WriteString(w, r.PostFormValue("name"))
            io.WriteString(w, "\n")
            io.WriteString(w, r.PostFormValue("pass"))
    }
}       

// panic treatment
func logsPanic (handle http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        defer func () {
            if x := recover(); x != nil {
                log.Printf("[%v] catch panic:%v", r.RemoteAddr, x)
            }
        }()
        handle(w, r)
    }
}


func main () {
    http.HandleFunc("/test1", func (w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "<h1>hello world</h1>")
    })

    http.HandleFunc("/test2", logsPanic(deal2))

    if err := http.ListenAndServe("localhost:10010", nil); err != nil {
        fmt.Println("listen server failed, error:", err)
        return
    }

}

  

Guess you like

Origin www.cnblogs.com/zhangxiaoj/p/11297002.html