http初识-浏览器访问服务器
package main
import (
"fmt"
"net/http"
)
func Hello(w http.ResponseWriter,r *http.Request) {
fmt.Println("handle hello")
fmt.Fprintf(w,"hello ")
}
func login(w http.ResponseWriter,r *http.Request) {
fmt.Println("handle login")
fmt.Fprintf(w,"login ")
}
func main() {
http.HandleFunc("/",Hello)
http.HandleFunc("/user/login",login)
err := http.ListenAndServe("0.0.0.0:8880",nil)
if err != nil {
fmt.Println("http listen Failed")
}
}
然后在浏览器中输入
在go的终端的输出如下:
客户端访问服务器
package main
import (
"fmt"
"io/IoUtil"
"net/http"
)
func main() {
res,err := http.Get("https://www.baidu.com/")
if err != nil {
fmt.Println("get err:",err)
return
}
data,err := IoUtil.ReadAll(res.Body)
if err != nil {
fmt.Println("get data err:",err)
return
}
fmt.Println(string(data))
}
输出如下
PS E:\golang\go_pro\src\safly> go run httpClient.go
<html>
<head>
<script> location.replace(location.href.replace("https://","http://")); </script>
</head>
<body>
<noscript><Meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>
</body>
</html>
PS E:\golang\go_pro\src\safly>
访问延迟处理
package main
import (
"fmt"
"net/http"
"net"
"time"
)
var url = []string{
"http://www.baidu.com","http://google.com","http://taobao.com",}
func main() {
for _,v := range url {
//type Client struct{}
c := http.Client{
//type Transport struct {}
Transport: &http.Transport {
//Dial func(network,addr string) (net.Conn,error)
Dial:func(network,addr string) (net.Conn,error){
timeout := time.Second*2
return net.DialTimeout(network,addr,timeout)
},},}
resp,err := c.Head(v)
if err != nil {
fmt.Printf("head %s Failed,err:%v\n",v,err)
continue
}
fmt.Printf("head succ,status:%v\n",resp.Status)
}
}
输出如下:
PS E:\golang\go_pro\src\safly> go run httpClient.go
head succ,status:200 OK
head http://google.com Failed,err:Head http://google.com: dial tcp 216.58.200.46:80: i/o timeout
head succ,status:200 OK
PS E:\golang\go_pro\src\safly>
回写form表单、并提交
package main
import (
"io"
// "log"
"net/http"
)
const form = `<html><body><form action="#" method="post" name="bar">
<input type="text" name="in"/>
<input type="text" name="in"/>
<input type="submit" value="Submit"/>
</form></body></html>`
func FormServer(w http.ResponseWriter,request *http.Request) {
w.Header().Set("Content-Type","text/html")
switch request.Method {
case "GET":
io.WriteString(w,form)
case "POST":
request.ParseForm()
io.WriteString(w,request.Form["in"][1])
io.WriteString(w,"\n")
io.WriteString(w,request.FormValue("in"))
}
}
/* func HandleFunc(pattern string,handler func(ResponseWriter,*Request)) { DefaultServeMux.HandleFunc(pattern,handler) } */
func main() {
http.HandleFunc("/test2",FormServer)
if err := http.ListenAndServe(":8088",nil); err != nil {
}
}