Hello, I'm sending messages over websocket. I have a "generic" MessageRequest and MessageResponse struct.
type MessageRequest struct { Type string `json:"type"` Payload interface{} `json:"payload"` } type MessageResponse struct { Type string `json:"type"` Payload interface{} `json:"payload"` } I'm trying to unmarshall this. m := new(MessageRequest) if e := json.Unmarshal(msg, m); e != nil { logrus.Error(e) return } Then I switch by MessageRequest.Type to know what kind of message was sent by the client. However, when I do something like payload, ok := m.Payload.(*MessageRequest) if !ok { //error } It isn't compatible to type *MessageRequest As a workaround I could imagine marshalling the interface again, then unmarshalling into the correct message payload type (e.g. ChatMessage) But that is unnecessary overhead. However it beats marshalling into map[string]interface and manually assigning values in terms of code readability. tmp, e := json.Marshal(m.Payload) if e != nil { logrus.Error(e) return } payload := new(model.ChatMessage) if e := json.Unmarshal(tmp, payload); e != nil { logrus.Error(e) return } vs pmap, ok := m.Payload.(map[string]interface{}) if !ok { logrus.Error("can not convert to map[string]interface{}") return } payload := new(model.ChatMessage) user := pmap["user"].(string) payload.User = user message := pmap["message"].(string) payload.Message = message tme := pmap["time"].(string) tmee, e := time.Parse(time.RFC3339, tme) if e != nil { logrus.Error("time parse error") return } payload.Time = tmee Is there a better solution to solve this? -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.