I tried some example from github and:
package main
import(
"bytes"
"fmt"
"net/http"
"encoding/json"
"time"
)
//User defines model for storing account details in database
type User struct {
Username string
//Password string `json:"-"`
//IsAdmin bool
CreatedAt time.Time
}
func main(){
mux := http.NewServeMux()
mux.HandleFunc("/echo", echoHandler)
http.ListenAndServe(":5000", mux)
}
func echoHandler(w http.ResponseWriter, r *http.Request){
user := User{} //initialize empty user
var bodyBuffer = new(bytes.Buffer)
bodyBuffer.ReadFrom(r.Body)
bodyBytes := bodyBuffer.Bytes()
fmt.Println("Received Body: ", string(bodyBytes[:]))
err := json.Unmarshal(bodyBytes, &user)
if err != nil{
panic(err)
}
fmt.Println(userJson)
w.Header().Set("Content-Type","application/json")
w.WriteHeader(http.StatusOK)
}
And when I call curl from powershell:
curl -d '{"Username":"noname"}' localhost:5000/echo
And the output is from console:
Received Body: {Username:noname}
2020/12/11 12:00:15 http: panic serving [::1]:52684: invalid character 'U' looking for beginning of object key string
goroutine 6 [running]:
net/http.(*conn).serve.func1(0xc00005caa0)
C:/Go/src/net/http/server.go:1801 +0x147
panic(0xa2b0a0, 0xc000004820)
C:/Go/src/runtime/panic.go:975 +0x499
main.echoHandler(0xacb5e0, 0xc0001340e0, 0xc000144000)
W:/projects/snippets/golang/parsing.go:39 +0x4ec
net/http.HandlerFunc.ServeHTTP(0xa8abf8, 0xacb5e0, 0xc0001340e0, 0xc000144000)
C:/Go/src/net/http/server.go:2042 +0x4b
net/http.(*ServeMux).ServeHTTP(0xc00001c300, 0xacb5e0, 0xc0001340e0, 0xc000144000)
C:/Go/src/net/http/server.go:2417 +0x1b7
net/http.serverHandler.ServeHTTP(0xc000134000, 0xacb5e0, 0xc0001340e0, 0xc000144000)
C:/Go/src/net/http/server.go:2843 +0xaa
net/http.(*conn).serve(0xc00005caa0, 0xacba60, 0xc00001c380)
C:/Go/src/net/http/server.go:1925 +0x8ad
created by net/http.(*Server).Serve
C:/Go/src/net/http/server.go:2969 +0x36d
The method: err := json.NewDecoder(r.Body).Decode(&user)
does not work also.
Probably, the error is that when I read the body in []byte array I can not see the quotes (") in the string. How can I make the server do not miss quotes in request body?