golang 服务端和客户端(二)

1.golang服务端

package main

import(
  "net/http"
)

func main(){
   //注册处理函数,用户连接,自动调用指定的处理函数
    http.HandleFunc("/",HandConn)
    //监听绑定
    http.ListenAndServe(":8080",nil)
}

func HandConn(w http.ResponseWriter,req *http.Request){
   w.Write([]byte("hello world"))
}

2.golang客户端

package main

import(
    "fmt"
    "net/http"
)

func main(){
    resp,err := http.Get("http://www.baidu.com")
    if err != nil {
        return
    }
    
    defer resp.Body.Close()
    
    fmt.Println("Status=",resp.Status)
    fmt.Println("StatusCode=",resp.StatusCode)
    fmt.Println("Header=",resp.Header)
   // fmt.Println("Body=",resp.Body)

    buf := make([]byte,1024)
    
    var tmp string
    for {
        n,err := resp.Body.Read(buf)
        if n== 0 {
            fmt.Println(''read Body err:",err)
            break
        }
        tmp += string(buf[:n])
    }
    
    fmt.Println(tmp)
}

猜你喜欢

转载自www.cnblogs.com/tomtellyou/p/11673940.html