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

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

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