go http编程
http的请求包
包含 请求行,请求头,空行,请求体
go的http编程
http server.go
package main
import "net/http"
func main() {
//注册处理函数,用户连接主动调用指定的函数
http.HandleFunc("/",handleFunction)//pattern为要请求的资源地址
//监听绑定
http.ListenAndServe("127.0.0.1:8000",nil)
}
//w 给客户端回复数据
//req读取客户端发送的数据
func handleFunction(w http.ResponseWriter,req*http.Request){
w.Write([]byte("hello world"))
}
http client.go
package main
import (
"fmt"
"net/http"
)
func main() {
res,err := http.Get("http://127.0.0.1:8000")
if err !=nil{
fmt.Println(err)
}
defer res.Body.Close();
if res.StatusCode == 200{
buff := make([]byte,1024)
var tmpstr string
for{
n,_:= res.Body.Read(buff)
if(n==0){
fmt.Println("文件已读完")
break
}
tmpstr +=string(buff[:n])
}
fmt.Println(tmpstr)
}else{
fmt.Println("请求失败")
}
}