推荐答案
在 Go 语言中,处理 HTTP 请求通常使用 net/http 包。以下是一个简单的示例,展示了如何创建一个 HTTP 服务器并处理 GET 和 POST 请求:
// www.javascriptcn.com code example
package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
fmt.Fprintf(w, "Hello, World!")
} else {
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
}
}
func formHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
r.ParseForm()
name := r.FormValue("name")
fmt.Fprintf(w, "Hello, %s!", name)
} else {
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
}
}
func main() {
http.HandleFunc("/hello", helloHandler)
http.HandleFunc("/form", formHandler)
fmt.Println("Server started at :8080")
http.ListenAndServe(":8080", nil)
}本题详细解读
1. 导入必要的包
首先,我们需要导入 net/http 包来处理 HTTP 请求和响应。fmt 包用于格式化输出。
import ( "fmt" "net/http" )
2. 定义处理函数
处理函数是实际处理 HTTP 请求的地方。每个处理函数接收两个参数:http.ResponseWriter 和 *http.Request。
http.ResponseWriter用于向客户端发送响应。*http.Request包含了客户端请求的所有信息。
func helloHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
fmt.Fprintf(w, "Hello, World!")
} else {
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
}
}3. 处理不同的 HTTP 方法
在处理函数中,可以通过 r.Method 来判断请求的类型(如 GET、POST 等),并根据不同的请求类型执行不同的逻辑。
if r.Method == "GET" {
fmt.Fprintf(w, "Hello, World!")
} else {
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
}4. 解析表单数据
对于 POST 请求,通常需要解析表单数据。可以使用 r.ParseForm() 来解析表单数据,然后通过 r.FormValue("key") 来获取具体的表单值。
r.ParseForm()
name := r.FormValue("name")
fmt.Fprintf(w, "Hello, %s!", name)5. 注册处理函数并启动服务器
使用 http.HandleFunc 将处理函数与特定的 URL 路径绑定。然后使用 http.ListenAndServe 启动 HTTP 服务器。
http.HandleFunc("/hello", helloHandler)
http.HandleFunc("/form", formHandler)
fmt.Println("Server started at :8080")
http.ListenAndServe(":8080", nil)6. 运行服务器
运行上述代码后,服务器将在 localhost:8080 上启动。你可以通过访问 http://localhost:8080/hello 来测试 GET 请求,或者通过 POST 请求向 http://localhost:8080/form 提交表单数据。