首页 > Web开发 > 详细

go http简单的表单处理

时间:2019-08-04 10:47:39      阅读:70      评论:0      收藏:0      [点我收藏+]
//表单处理
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")

    //Method 代表指定的http方法
    switch r.Method {
        case "GET":
            //io.WriteString(w, s string) 将字符串的s写入w中
            io.WriteString(w, form)
        case "POST":
            //func (*Request) PostFormValue
            //PostFormValue返回key为键查询r.PostForm字段得到结果[]string切片的第一个值
            io.WriteString(w, r.PostFormValue("name"))
            io.WriteString(w, "\n")
            io.WriteString(w, r.PostFormValue("pass"))
    }
}       

//panic 处理
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
    }

}

  

go http简单的表单处理

原文:https://www.cnblogs.com/zhangxiaoj/p/11297002.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!