使用 golang 写 一个 http 接收程序
下面是一个简单的示例,可以接收 POST 请求:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/receive", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
// 读取请求体
body := make([]byte, r.ContentLength)
_, err := r.Body.Read(body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// 输出请求体内容
fmt.Fprintf(w, "Received: %s", body)
} else {
http.Error(w, "Invalid request method", http.StatusBadRequest)
}
})
http.ListenAndServe(":8080", nil)
}
在终端运行 go run main.go,即可启动该程序。然后可以使用 curl 命令发送 POST 请求:
curl -X POST -d "Hello, world!" http://localhost:8080/receive
程序会输出:
Received: Hello, world!
这就是一个简单的 http 接收程序的实现。
原文地址: https://www.cveoy.top/t/topic/bUSI 著作权归作者所有。请勿转载和采集!