Good day. There is a small http handler. package main

func requestHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "hello world!") fmt.Println("Zapros") } 

Through the Advanced Rest Client (chrome) I send Post with the line:

  { "name": "Вася", "age": 35, "isAdmin": false} 

How do I process / parse this content in a handler?

    2 answers 2

    If your requests are of the same type in the form of json , you can describe this structure and write the request into it, in the future it will be convenient to work:

     package main import ( "fmt" "encoding/json" "io/ioutil" "net/http" ) //структура описывающая запрос type Foo struct { Name string `json:"name"` Age int `json:"age"` IsAdmin bool `json:"isAdmin"` } func requestHandler(w http.ResponseWriter, r *http.Request) { var resp Foo //читаем тело запроса body, err := ioutil.ReadAll(r.Body) //проверяем на наличие ошибки if err != nil { fmt.Fprintf(w, "err %q\n", err, err.Error()) } else { //если все нормально - пишем по указателю в структуру err = json.Unmarshal(body, &resp) if err != nil { fmt.Println(w, "can't unmarshal: ", err.Error()) } } //выводим полученные данные (можно делать с данными все, что угодно) fmt.Fprintf(w, "Name:", resp.Name, "Age:", resp.Age, "IsAdmin:", resp.IsAdmin) } 

      somewhere so

       b, err := ioutil.ReadAll(r.Body) if err == nil { fmt.Fprintf(w, "%q", b) fmt.Fprintf(w, "ok") } else { fmt.Fprintf(w, "err %q\n", err) }