推荐答案
在 Go 语言中,net/http 包是用于构建 HTTP 客户端和服务器的标准库。以下是 net/http 包的基本用法:
1. 创建 HTTP 服务器
// www.javascriptcn.com code example
package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
}
func main() {
http.HandleFunc("/", helloHandler)
http.ListenAndServe(":8080", nil)
}2. 创建 HTTP 客户端
// www.javascriptcn.com code example
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
resp, err := http.Get("https://example.com")
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(string(body))
}3. 处理请求参数
// www.javascriptcn.com code example
package main
import (
"fmt"
"net/http"
)
func queryHandler(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
fmt.Fprintf(w, "Hello, %s!", name)
}
func main() {
http.HandleFunc("/query", queryHandler)
http.ListenAndServe(":8080", nil)
}4. 处理 POST 请求
// www.javascriptcn.com code example
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func postHandler(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "Error reading request body", http.StatusInternalServerError)
return
}
defer r.Body.Close()
fmt.Fprintf(w, "Received: %s", string(body))
}
func main() {
http.HandleFunc("/post", postHandler)
http.ListenAndServe(":8080", nil)
}本题详细解读
1. HTTP 服务器
在 Go 中,使用 http.HandleFunc 函数可以将一个路径与一个处理函数绑定。http.ListenAndServe 函数用于启动 HTTP 服务器,并监听指定的地址和端口。
2. HTTP 客户端
使用 http.Get 函数可以发送一个 HTTP GET 请求到指定的 URL。http.Response 结构体包含了响应的状态码、头部和响应体等信息。通过 ioutil.ReadAll 函数可以读取响应体的内容。
3. 处理请求参数
在 HTTP 请求中,查询参数可以通过 r.URL.Query().Get("key") 方法获取。r.URL.Query() 返回一个 url.Values 类型的映射,可以通过键名获取对应的值。
4. 处理 POST 请求
对于 POST 请求,请求体可以通过 r.Body 读取。使用 ioutil.ReadAll 函数可以读取整个请求体内容。在处理完请求体后,应该调用 r.Body.Close() 关闭请求体,以释放资源。
通过以上示例,可以掌握 net/http 包的基本用法,能够构建简单的 HTTP 服务器和客户端,并处理常见的 HTTP 请求。