1
func deserialize(request *http.Request,typ reflect.Type) (interface{}, *httpNet.HandlerError){

    data,e:=ioutil.ReadAll(request.Body)
    fmt.Println(string(data))
    if e !=nil{
        return nil,&httpNet.HandlerError{e,"could not read request",http.StatusBadRequest}
    }

    v:=typ.Elem()
    payload:=reflect.New(v).Elem().Interface()

    eaa:= json.NewDecoder(request.Body).Decode(payload)

    if e!=nil{
        fmt.Println(eaa.Error())
    }
    fmt.Println(payload)
    fmt.Println(reflect.ValueOf(payload)
        )
    return payload,nil

}

to call it:

r,_:= deserialize(request,reflect.TypeOf(&testData{}))

It does not throw errors and looks completely valid operation to me , but the result is an empty structure of expecting type.

Whats the problem with that?

1 Answer 1

4

The problem is that you are passing a non pointer instance of the type:

payload:=reflect.New(v).Elem().Interface()

Means "allocate a new pointer to the type, then take the value of it, and extract it as interface{}.

You should just keep it at:

payload:=reflect.New(v).Interface()

BTW It's also redundant that you are passing the type of a pointer, extracting its Elem(), then allocating a pointer. Do something like this:

if type.Kind() == reflect.Ptr {
   typ = typ.Elem()
}

payload := reflect.New(typ).Interface()

then you can pass both pointers and non pointers to the function.

Edit: Working playground example: http://play.golang.org/p/TPafxcpIU5

Sign up to request clarification or add additional context in comments.

3 Comments

tanx , tested it but I got the same result
@Mohsen I'm doing the exact same thing in my code and it works perfectly. Are you sure there's data coming in?
@Mohsen I've created a simplified working example in the playground. See the answer's edited text.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.