Не удается получить параметр записи в Golang из запроса AJAX - PullRequest
0 голосов
/ 30 декабря 2018

На стороне клиента у меня есть код:

    let response = await fetch('/getInfo', {
      credentials: 'same-origin',
      method: 'POST',
      body: JSON.stringify({filename: "file.jpg"})
    });

Код на стороне сервера:

    fmt.Println(c.PostForm("filename")) // empty

Почему он пуст?Как получить значение c.PostForm ("имя файла")?

1 Ответ

0 голосов
/ 30 декабря 2018

Этот код декодирует объект JSON из тела запроса:

// Request is structure to encode request body
type Request struct {
    FileName string `json:"filename"`
}

// ServeHTTP is request handler
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    decoder := json.NewDecoder(r.Body)
    var req Request
    err := decoder.Decode(&req)
    if err != nil {
        // handle error
        return
    }
    // process request
}
...