gpt4 book ai didi

curl - 如何接受来自 Go 的 POST 请求并将输出写入文件?

转载 作者:数据小太阳 更新时间:2023-10-29 03:28:33 24 4
gpt4 key购买 nike

首先,我尝试在 Go 中创建一个日志记录服务,它是一个轻量级服务器,它接受带有来 self 的服务的日志数据的 POST 请求。我正在用 Go 编写此服务,因为它应该很快并且可以同时处理大量 POST 请求。我的逻辑是否正确?

无论如何,这是我的问题。我正在发送这样的 POST 请求来测试:
curl -H "Content-Type: application/json"-X POST -d '{"hello":"world"}' http://localhost:8080/log

到目前为止,这是我的 Go 脚本:

package main

import (
"fmt"
"log"
"net/http"
)

func logger(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
fmt.Println(r.Form)
fmt.Println(r.FormValue("hello"))
}

func main() {
http.HandleFunc("/log", logger)
log.Fatal(http.ListenAndServe(":8080", nil))
}

正在输出: map []

这是为什么呢?如何将 POST 数据写入服务器上的文件?

非常感谢!W

最佳答案

r.Method 包含接收到的请求类型(GET、POST、HEAD、PUT 等)。

您可以使用 ioutilr.Body 读取数据,并使用相同的包将该数据写入文件。

这仅用于处理 POST 方法,读取数据并写入文件 (output.txt)。

if r.Method == "POST" {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Errorf("Error during reading body: %v", err)
}

if err := ioutil.WriteFile("output.txt", body, 0644); err != nil {
fmt.Errorf("Error during writing data: %v", err)
}
}

关于curl - 如何接受来自 Go 的 POST 请求并将输出写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30537097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com