Of course after I ask my question I find the answer on my own. It's always like this.
The solution is to change type MessageRequest struct { Type string `json:"type"` Payload json.RawMessage `json:"payload"` } So the payload isn't unmarshalled. Now, after the MessageRequest is unmarshalled I can check for the type and then payload := new(model.ChatMessage) if e := json.Unmarshal(m.Payload, payload); e != nil { logrus.Error(e) return } On Friday, December 14, 2018 at 8:17:25 PM UTC+1, Darko Luketic wrote: > > 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.