目的
go语言实现处理表单输入, 接受Get参数, 打印获取到数据
实现
主要使用net/http包实现,使用net/http包中ListenAndServe
1
| func ListenAndServe(addr string, handler Handler) error
|
监听TCP网络地址addr然后调用具有handler的Serve去处理连接请求.通常情况下Handler是nil,使用默认的DefaultServeMux
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| package main
import( "fmt" "net/http" "log" "strings" )
func main() { fmt.Println("hello, world")
http.HandleFunc("/", sayHelloName) err := http.ListenAndServe(":9090", nil) if err != nil{ log.Fatal("ListenAndServer:", err) } }
func sayHelloName(w http.ResponseWriter, r *http.Request){ r.ParseForm() fmt.Println(r.Form) fmt.Println("method:", r.Method) fmt.Println("path", r.URL.Path) fmt.Println("Scheme", r.URL.Scheme) fmt.Println(r.Form["url_long"])
fmt.Fprintf(w, "hello, world ")
if(r.Form != nil){
for k, v := range r.Form { fmt.Println("key: ", k) fmt.Println("val: ", strings.Join(v, "")) fmt.Fprintf(w, strings.Join(v, "")) } } }
|
测试
访问http://localhost:9090/?username=pangxieke
返回