douyuan4697 2015-05-29 18:56
浏览 448

如何接受来自Go的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

  • 写回答

2条回答 默认 最新

  • douzi7711 2015-05-29 19:04
    关注

    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)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度