在golang中读取通过axios发送的一个post参数

Read a post parameter sent through axios in golang

我是golang的新手,正在尝试理解这一点。我面临以下问题。

我发送 axios post 如下

const options = {
  data: {
    test: this.state.value,
  },
  method: 'POST',
  url: `/test`,
};
console.log(options)
axios.request(options).then(
  () => {
    console.log(this.state.value);
  },
  (error) => {
    console.log(error);
  },
);

现在在 Go 部分,我正在尝试阅读它。但我不知道如何在 Go 中阅读它。我尝试使用以下代码,但它不起作用。它仅打印 test Value。谁能帮我?谢谢。

func routetest(w http.ResponseWriter, r *http.Request) {
    test, _ := param.String(r, "test")
    fmt.Printf("test Value")
    fmt.Printf(test)
    fmt.Printf("test Value")
}

更新代码

func routeTest(w http.ResponseWriter, r *http.Request) {
    type requestBody struct {
        test string `json:"test"`
    }
    body := requestBody{}
    decoder := json.NewDecoder(r.Body)
    if err := decoder.Decode(&body); err != nil {
        // some error handling
        return
    }
    defer r.Body.Close()
    test := body.test
    fmt.Printf(test)
}

最简单的方法是将您的正文解码为类似 json 的结构,然后从那里获取您的值

import (
    "encoding/json"
    "fmt"
    "net/http"
)

type requestBody struct {
    Test       string `json:"test"`
}

func routeTest(w http.ResponseWriter, r *http.Request) {
    body := requestBody{}
    decoder := json.NewDecoder(r.Body)
    if err := decoder.Decode(&body); err != nil {
        // some error handling
        return
    }
    defer r.Body.Close()
    test := body.Test
    fmt.Printf(test)
}