Search code examples
mysqlgogorillamux

Error while converting json to struct from Go


 func MakeMap(w http.ResponseWriter, r *http.Request) {
    // userInfo := context.Get(r, "userInfo").(model.User)
    type _getData struct {
        Title string   `json:"title"`
        Tag   []string `json:"tag"`
    }
    var getData _getData
    err := json.NewDecoder(r.Body).Decode(&getData)
    if err != nil {
        panic(err.Error())
    }
    fmt.Print(getData)

}

When I run the above code, I get the following error

2021/08/24 13:56:54 http: panic serving 127.0.0.1:50619: runtime error: invalid memory address or nil pointer dereference
goroutine 23 [running]:
net/http.(*conn).serve.func1(0x140001e9180)
        /usr/local/go/src/net/http/server.go:1824 +0x108
panic(0x10505b860, 0x10522f240)
        /usr/local/go/src/runtime/panic.go:971 +0x3f4
traveling/controller/mapController.MakeMap(0x1050b5630, 0x140001f40e0, 0x1400018aa00)
/Users/choeyunseog/traveling/traveling/controller/mapController/mapController.go:20 +0x3c

I've just started studying, I'm not sure why I'm having this problem, please help

enter image description here

err := json.NewDecoder(r.Body).Decode(&getData) 

I get the following error when i change code line 20 like above

 2021/08/24 14:16:44 http: panic serving 127.0.0.1:51396: invalid character '-' in numeric literal
goroutine 23 [running]:
net/http.(*conn).serve.func1(0x140001e9360)
        /usr/local/go/src/net/http/server.go:1824 +0x108
panic(0x100d85d00, 0x14000206070)
        /usr/local/go/src/runtime/panic.go:971 +0x3f4
traveling/controller/mapController.MakeMap(0x100df1630, 0x140001f40e0, 0x1400018aa00)
        /Users/choeyunseog/traveling/traveling/controller/mapController/mapController.go:24 +0x194
net/http.HandlerFunc.ServeHTTP(0x100de75d8, 0x100df1630, 0x140001f40e0, 0x1400018aa00)
        /usr/local/go/src/net/http/server.go:2069 +0x40

Solution

  • To get the multipart form data from a POST/PUT/PATCH request's body you can use the ParseMultipartForm method to parse the body and then access the data through the PostForm field. Or you can use FormValue to get just the first value associated with the form's field.

    maxMemory := 32<<20
    if err := r.ParseMultipartForm(maxMemory); err != nil {
        panic(err)
    }
    
    fmt.Println(_getData{
        Title: r.FormValue("title"), // FormValue returns string
        Tag:   r.PostForm["tag[]"],  // PostForm is a map of []string
    })