go语言http相关
1. 回调函数
和C语言一样,在函数参数里加上一个函数指针,传变量的时候将函数指针传进去即可调用
type FUNCP func(x int, y bool) int
func callBack(x int, y bool, p FUNCP) int {
fmt.Println("调用回调函数", p(x, y))
return x
}
func han(x int, y bool) int {
fmt.Println("这里是回调函数")
return x
}
func main() {
callBack(1, true, han)
}
2. http请求的接收与响应
-
定义自己的回调函数
func handler(w http.ResponseWriter, req *http.Request)
- w:回写给客户端的数据
- req:读取到的客户端请求数据
-
设置响应的回调函数
func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))
-
设置监听
func ListenAndServe(addr string, handler Handler) error
- addr:服务器的ip:port
- 回调函数,通常传nil表示默认
import "net/http"
func handle(w http.ResponseWriter, r *http.Request) {
// w 表示写回给客户端的数据
// r 表示从客户端接收到的数据
w.Write([]byte("hello hehe"))
}
func main() {
http.HandleFunc("/itcast.txt", handle)
http.ListenAndServe(":8000", nil)
}
func helloServer(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("http server"))
fmt.Println("Method =", req.Method)
fmt.Println("URL =", req.URL)
fmt.Println("Proto =", req.Proto)
fmt.Println("Header =", req.Header)
fmt.Println("Body =", req.Body)
fmt.Println("RemoteAddr =", req.RemoteAddr)
fmt.Println("Close =", req.Close)
}
func main() {
http.HandleFunc("/", helloServer)
http.ListenAndServe(":8000", nil)
}
3. go语言实现http客户端
func Get(url string) (resp *Response, err error)
-
参数:待请求的url。注意:必须带有http://开头
-
返回值:
-
Response:服务器回复的应答包
-
type Response struct { Status string // 例如"200 OK" StatusCode int // 例如200 Proto string // 例如"HTTP/1.0" ProtoMajor int // 例如1 ProtoMinor int // 例如0 // Header保管头域的键值对。 // 如果回复中有多个头的键相同,Header中保存为该键对应用逗号分隔串联起来的这些头的值 // (参见RFC 2616 Section 4.2) // 被本结构体中的其他字段复制保管的头(如ContentLength)会从Header中删掉。 // // Header中的键都是规范化的,参见CanonicalHeaderKey函数 Header Header // Body代表回复的主体。 // Client类型和Transport类型会保证Body字段总是非nil的,即使回复没有主体或主体长度为0。 // 关闭主体是调用者的责任。 // 如果服务端采用"chunked"传输编码发送的回复,Body字段会自动进行解码。 Body io.ReadCloser // ContentLength记录相关内容的长度。 // 其值为-1表示长度未知(采用chunked传输编码) // 除非对应的Request.Method是"HEAD",其值>=0表示可以从Body读取的字节数 ContentLength int64 // TransferEncoding按从最外到最里的顺序列出传输编码,空切片表示"identity"编码。 TransferEncoding []string // Close记录头域是否指定应在读取完主体后关闭连接。(即Connection头) // 该值是给客户端的建议,Response.Write方法的ReadResponse函数都不会关闭连接。 Close bool // Trailer字段保存和头域相同格式的trailer键值对,和Header字段相同类型 Trailer Header // Request是用来获取此回复的请求 // Request的Body字段是nil(因为已经被用掉了) // 这个字段是被Client类型发出请求并获得回复后填充的 Request *Request // TLS包含接收到该回复的TLS连接的信息。 对未加密的回复,本字段为nil。 // 返回的指针是被(同一TLS连接接收到的)回复共享的,不应被修改。 TLS *tls.Co
-
重要注意:Body是一个指针类型 – read,close
-
func main() {
//resp, err := http.Get("http://127.0.0.1:8001/abc.txt")
resp, err := http.Get("http://www.baidu.com")
if err != nil {
panic(err)
}
fmt.Println(resp.Body)
fmt.Println(resp.Close)
defer resp.Body.Close()
buf := make([]byte, 4096)
for {
n, err := resp.Body.Read(buf)
if n == 0 {
break
}
if err != nil && err != io.EOF {
panic(err)
}
fmt.Println(string(buf[:n]))
}
}