英文:
How do I accept POST requests from Go and write output to a file?
问题
首先,我正在尝试在Go中创建一个日志记录服务,它是一个轻量级的服务器,接受来自我的服务的日志数据的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数据写入服务器上的文件?
非常感谢!
英文:
First of all, I'm trying to create a logging service in Go, where it is a lightweight server accepting POST requests with log data from my service. I'm writing this service in Go because it is supposed to be fast and handle a lot of POST requests at once. Is my logic sound there?
Anyways, this is my issue. I'm sending POST requests like this to test:
curl -H "Content-Type: application/json" -X POST -d '{"hello":"world"}' http://localhost:8080/log```
And here is my Go script so far:
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))
}
It is outputting:
```map []```
Why is that? How could I write the POST data to a file on the server?
Thank you very much!
W
</details>
# 答案1
**得分**: 1
`r.Method` 包含接收到的请求类型(GET、POST、HEAD、PUT 等)。
您可以使用 `ioutil` 从 `r.Body` 中读取数据,并使用相同的包将该数据写入文件。
这是用于处理仅限于 **POST** 方法的情况,读取数据并将其写入文件(output.txt)。
```go
if r.Method == "POST" {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Errorf("读取请求体时发生错误:%v", err)
}
if err := ioutil.WriteFile("output.txt", body, 0644); err != nil {
fmt.Errorf("写入数据时发生错误:%v", err)
}
}
英文:
r.Method
contains type of received request (GET, POST, HEAD, PUT, etc.).
You can read data from r.Body
with ioutil
and write that data into the file with the same package.
This is for handling only POST method, reading data and writing into file (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)
}
}
答案2
得分: 0
你没有POST一个表单,而是在请求体中发送JSON数据。
直接读取数据:
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Println("ERROR:", err)
}
英文:
You're not POST'ing a form, you're sending json data in the request body.
Read the data directly:
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Println("ERROR:", err)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论