http编程
一、Http协议
1. 什么是协议?
协议,是指通信的双方,在通信流程或内容格式上,共同遵守的标准。
2. 什么是http协议?
http协议,是互联网中最常见的网络通信标准。
3. http协议的特点
①通信流程:断开式(无状态)
断开式:http协议每次响应完成后,会断开与客户端的连接
无状态:由于服务器断开了之前的连接,就无法知晓连接间的关系
②内容格式:消息头和消息体
二、http编程概述
HTTP(HyperText Transfer Protocol,超文本传输协议)是互联网上应用最为广泛的一种网络协议,定义了客户端和服务端之间请求和响应的传输标准。Go语言标准库内建提供了net/http包,涵盖了HTTP客户端和服务端的具体实现。使用net/http包,我们可以很方便地编写HTTP客户端或服务端的程序。
特点:
a. Go原生支持http,import(“net/http”)
b. Go的http服务性能和nginx比较接近
c. 几行代码就可以实现一个web服务
三、客户端与服务端
1. 服务端
package main
import (
"fmt"
"net/http"
)
//w, 给客户端回复数据
//r, 读取客户端发送的数据
func HandConn(w http.ResponseWriter, r *http.Request) {
fmt.Println("r.Method = ", r.Method)
fmt.Println("r.URL = ", r.URL)
fmt.Println("r.Header = ", r.Header)
fmt.Println("r.Body = ", r.Body)
w.Write([]byte("hello go")) //给客户端回复数据
}
func main() {
//注册处理函数,用户连接,自动调用指定的处理函数
http.HandleFunc("/", HandConn)
//监听绑定
http.ListenAndServe(":8000", nil)
}
package mainimport("fmt"
"net/http")
func Hello(w http.ResponseWriter, r*http.Request) {
fmt.Println("r.Method =", r.Method)
fmt.Println("r.URL =", r.URL)
fmt.Println("r.Header =", r.Header)
fmt.Println("r.Body =", r.Body)
fmt.Println("handle hello")
fmt.Fprintf(w,"hello")
}
func login(w http.ResponseWriter, r*http.Request) {
fmt.Println("handle login")
fmt.Fprintf(w,"login")
}
func history(w http.ResponseWriter, r*http.Request) {
fmt.Println("handle history")
fmt.Fprintf(w,"history")
}
func main() {
http.HandleFunc("/", Hello)
http.HandleFunc("/user/login", login)
http.HandleFunc("/user/history", history)
err := http.ListenAndServe("0.0.0.0:8880", nil)if err !=nil {
fmt.Println("http listen failed")
}
}
http_server.go
2. 客户端
package main
import (
"fmt"
"net/http"
)
func main() {
//resp, err := http.Get("http://www.baidu.com")
resp, err := http.Get("http://127.0.0.1:8000")
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, 4*1024)
var tmp string
for {
n, err := resp.Body.Read(buf)
if n == 0 {
fmt.Println("read err = ", err)
break
}
tmp += string(buf[:n])
}
//读取网页内容,打印出来
fmt.Println("tmp = ", tmp)
}