在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
package main import ( "fmt" "net/http" ) func hello(w http.ResponseWriter, r *http.Request) { fmt.Println("handle hello") fmt.Fprintf(w, "hello12345") } func index (w http.ResponseWriter, r *http.Request) { //Fprintf根据format参数生成格式化的字符串并写入w。返回写入的字节数和遇到的任何错误 fmt.Fprintf(w, "this is index") } func main () { //HandleFunc注册一个处理器函数handler和对应的模式pattern //实现路由功能, hello 为函数名 http.HandleFunc("/", hello) http.HandleFunc("/index", index) //ListenAndServe监听srv.Addr指定的TCP地址,并且会调用Serve方法接收到的连接。如果srv.Addr为空字符串,会使用":http"。 err := http.ListenAndServe("0.0.0.0:8080", nil) if err != nil { fmt.Println("http listen failed") } } 2.客户端
//http 客户端 package main import ( "fmt" "net/http" "io/ioutil" ) func main () { res, err := http.Get("http://www.baidu.com") if err != nil { fmt.Println("get faield,error:,", err) return } data, err := ioutil.ReadAll(res.Body) if err != nil { fmt.Println("read err, error:,", err) return } fmt.Println(string(data)) } 3. head请求
//head请求实例子 package main import ( "fmt" "net/http" "time" "net" ) var url = []string{ "http://www.baidu.com", "http://www.gegole.com", "http://www.taobao.com", } func main () { for _, v := range url { //自己建立客户端 client := http.Client{ Transport: &http.Transport { Dial: func(network, addr string) (net.Conn, error) { //设置超时时间 timeout := 2 * time.Second return net.DialTimeout(network, addr, timeout) }, }, } resp, err := client.Head(v) if err != nil { fmt.Println("send head failed, error:", err) continue } fmt.Printf("head succ, status: %v \n", resp.Status) } }
|
请发表评论