http编程
1) Go原生支持 http : import ("net/http") 2) Go 的 http 服务性能和 nginx 比较接近 3) 几行代码就可以实现一个 web 服务
http 服务端
// 示例代码: package main import ( "fmt" "net/http" ) func Hello(w http.ResponseWriter, r *http.Request){ fmt.Println("hello world\n") fmt.Fprintf(w,"hello world") // 返回响应 } func main(){ http.HandleFunc("/",Hello) // 路由;第一个参数是路径,第二个参数是视图函数 err := http.ListenAndServe("0.0.0.0:8080",nil) // 监听并等待请求 if err != nil{ fmt.Println("http listened failed") } }
http 客户端
// 示例代码: package main import ( "fmt" "net/http" "io/ioutil" ) func main(){ ret,err := http.Get("https://www.baidu.com/") // 向一个服务器发送 GET 请求;返回的数据都在 ret.Body 里面 if err != nil { fmt.Println("get err:",err) return } data,err := ioutil.ReadAll(ret.Body) // 返回的数据都在 ret.Body 里面 if err != nil { fmt.Println("get data err:",err) return } fmt.Printf("Type:%T\n",data) fmt.Println(string(data)) } // 运行结果: [[email protected] example01_http_client]# go run main/main.go Type:[]uint8 <html> <head> <script> location.replace(location.href.replace("https://","http://")); </script> </head> <body> <noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript> </body> </html> [[email protected] example01_http_client]#
http常见请求方法
1)Get请求 2)Post请求 3)Put请求 4)Delete请求 5)Head请求 -- > 只请求页面的头部
发送 HEAD 请求
// 示例代码: package main import ( "fmt" "net/http" ) var urls = []string{ "http://www.baidu.com", "http://www.google.com", "http://www.taobao.com", } func main(){ for _,v := range urls{ resp,err := http.Head(v) // 发送 Head 请求 if err != nil { fmt.Printf("head %s failed,err:%v\n",v,err) continue } fmt.Printf("head success,status:%v\n",resp.Status) // resp.Status --> 状态码 } } // 运行结果: [[email protected] example01_http_head_request]# go run main/main.go head success,status:200 OK head http://www.google.com failed,err:Head http://www.google.com: dial tcp 75.126.2.43:80: connect: connection timed out head success,status:200 OK [[email protected] example01_http_head_request]# // 自定义超时时间 // 示例代码: package main import ( "fmt" "net/http" "time" "net" ) var urls = []string{ "http://www.baidu.com", "http://www.google.com", "http://www.taobao.com", } func main(){ for _,v := range urls{ c := http.Client{ // 自定义客户端 Transport: &http.Transport{ Dial: func(network, addr string) (net.Conn, error){ timeout := time.Second * 2 // 自定义超时时间 return net.DialTimeout(network, addr, timeout) }, }, } start := time.Now() resp,err := c.Head(v) // 用自定义的客户端发送请求 end := time.Now() interval := end.Sub(start) fmt.Println("interval:",interval) //resp,err := http.Head(v) // 发送 Head 请求 if err != nil { fmt.Printf("head %s failed,err:%v\n",v,err) continue } fmt.Printf("head success,status:%v\n",resp.Status) // resp.Status --> 状态码 } } // 运行结果: [[email protected] example01_http_head_request]# go run main/main.go interval: 171.062376ms head success,status:200 OK interval: 2.000789206s head http://www.google.com failed,err:Head http://www.google.com: dial tcp 69.63.184.142:80: i/o timeout interval: 749.542763ms head success,status:200 OK [[email protected] example01_http_head_request]#
http 常见状态码:
http.StatusContinue = 100 http.StatusOK = 200 http.StatusFound = 302 http.StatusBadRequest = 400 http.StatusUnauthorized = 401 http.StatusForbidden = 403 http.StatusNotFound = 404 http.StatusInternalServerError = 500
表单处理:
// 示例代码: package main import ( "io" "net/http" ) // 常量 form 是一段 html 代码 const form = `<html><body><form action="#" method="post" name="bar"> <input type="text" name="in"/> <input type="text" name="in"/> <input type="submit" value="Submit"/> </form></html></body>` func SimpleServer(w http.ResponseWriter, request *http.Request) { // 请求信息都在 request 中 io.WriteString(w, "<h1>hello, world</h1>") // 返回给客户端一段html代码 } func FormServer(w http.ResponseWriter, request *http.Request) { w.Header().Set("Content-Type", "text/html") // w.Head().Set(key,val) ---> 设置响应头 switch request.Method { // request.Method --> 请求方法 case "GET": io.WriteString(w, form) // 把 form 表单返回给客户端 case "POST": request.ParseForm() // 需要先解析表单 io.WriteString(w, request.Form["in"][0]) // request.Form["in"] 是一个数组 io.WriteString(w, "\n") io.WriteString(w, request.FormValue("in")) // request.FormValue("in") ---> 获取表单中的值(name重复时,取最近的一个);推荐使用这个 } } func main() { http.HandleFunc("/test1", SimpleServer) http.HandleFunc("/test2", FormServer) if err := http.ListenAndServe(":8088", nil); err != nil { } }
原文地址:https://www.cnblogs.com/neozheng/p/11355592.html
时间: 2024-10-17 21:07:06