课程进度 67% · 第16/23章第16/23章 · 标签 1/2
— 1 —
HTTP编程
go
1
// HTTP服务器
2
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
3
fmt.Fprintf(w, "Hello, %s!", r.URL.Query().Get("name"))
4
})
5
http.ListenAndServe(":8080", nil)
6
7
// HTTP客户端
8
resp, _ := http.Get("https://api.example.com/data")
9
defer resp.Body.Close()
10
body, _ := io.ReadAll(resp.Body)
11
fmt.Println(string(body))
— 2 —
TCP/UDP
go
1
// TCP服务器
2
listener, _ := net.Listen("tcp", ":8080")
3
conn, _ := listener.Accept()
4
io.Copy(conn, conn) // 回显
5
conn.Close()
6
7
// UDP
8
addr, _ := net.ResolveUDPAddr("udp", ":8081")
9
conn, _ := net.ListenUDP("udp", addr)
10
buf := make([]byte, 1024)
11
n, _, _ := conn.ReadFromUDP(buf)
HTTPTCPUDPWebSocketTLS