咱们能够使用http包创建Web服务器web
1 package main 2 3 import ( 4 "fmt" 5 "log" 6 "strings" 7 "net/http" 8 ) 9 10 func sayHelloName(w http.ResponseWriter,r *http.Request){ 11 r.ParseForm() // 解析参数 12 fmt.Println(r.Form) 13 fmt.Println("path",r.URL.Path) 14 fmt.Println("scheme",r.URL.Scheme) 15 fmt.Println(r.Form["url_long"]) 16 for k,v := range r.Form{ 17 fmt.Println("key",k) 18 fmt.Println("val",strings.Join(v,"")) 19 } 20 fmt.Fprintf(w,"Hello astaxie!") 21 } 22 23 func main(){ 24 http.HandleFunc("/",sayHelloName) // 设置访问的路由 25 err := http.ListenAndServe(":9090",nil) // 设置监听的端口 26 if err != nil{ 27 log.Fatal("ListenAndServer Failed:",err) 28 } 29 }
上面这个代码,咱们build以后,而后执行web.exe,这个时候其实已经在9090端口监听http连接请求了。浏览器
在浏览器输入http://localhost:9090
服务器
能够看到浏览器页面输出了Hello astaxie!
函数
能够换一个地址试试:http://localhost:9090/?url_long=111&url_long=222
ui
看看浏览器输出的是什么,服务器输出的是什么?url
在服务器端输出的信息以下:spa
用户访问Web以后服务器端打印的信息code
咱们看到上面的代码,要编写一个Web服务器很简单,只要调用http包的两个函数就能够了。orm