go语言实现简单的http客户端与服务器
服务器代码
package main
import (
"fmt"
"net/http"
)
func main(){
http.HandleFunc("/",HandConn)
http.ListenAndServe(":8080",nil)
}
func HandConn(w http.ResponseWriter,req *http.Request){
w.Write([]byte("hello go"))
fmt.Println("req.Method = ",req.Method)
fmt.Println("req.Header = ",req.Header)
fmt.Println("req.URL = ",req.URL)
fmt.Println("req.Body = ",req.Body)
}
客户端代码
package main
import (
"fmt"
"net/http"
)
func main(){
resp,err := http.Get("http://www.ytu.edu.cn")
if err != nil{
fmt.Println("http.Get err:",err)
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*4)
var tmp string
for{
n,err1 := resp.Body.Read(buf)
if n == 0 {
fmt.Println("resp.Body.Read err:",err1)
fmt.Println("ok")
break
}
tmp += string(buf[:n])
}
fmt.Println("tmp = ",tmp)
}