在Go语言中,要读取HTTP请求的Body内容,可以使用ioutil.ReadAll()
函数或者http.Request.Body
来实现。以下是示例代码:
使用 ioutil.ReadAll() 函数:
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "Failed to read request body", http.StatusInternalServerError)
return
}
fmt.Println(string(body))
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
使用 http.Request.Body:
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
body := make([]byte, r.ContentLength)
r.Body.Read(body)
fmt.Println(string(body))
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
以上代码演示了如何读取HTTP请求的Body内容,并将其打印输出。你可以根据具体的需求对读取到的数据进行进一步处理。
内容由零声教学AI助手提供,问题来源于学员提问