github.com/martinohmann/rfoutlet@v1.2.1-0.20220707195255-8a66aa411105/internal/command/envelope.go (about)

     1  package command
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  )
     7  
     8  // Envelope defines a command envelope which hold the command type and the raw
     9  // json data of the command.
    10  type Envelope struct {
    11  	Type Type
    12  	Data *json.RawMessage
    13  }
    14  
    15  // Unpack unpacks the contents of a command envelope into the correct
    16  // type.
    17  func Unpack(envelope Envelope) (cmd Command, err error) {
    18  	switch envelope.Type {
    19  	case OutletType:
    20  		cmd = &OutletCommand{}
    21  	case GroupType:
    22  		cmd = &GroupCommand{}
    23  	case IntervalType:
    24  		cmd = &IntervalCommand{}
    25  	case StatusType:
    26  		cmd = &StatusCommand{}
    27  	default:
    28  		return nil, fmt.Errorf("unknown command type %q", envelope.Type)
    29  	}
    30  
    31  	if envelope.Data != nil {
    32  		err = json.Unmarshal(*envelope.Data, cmd)
    33  		if err != nil {
    34  			return nil, fmt.Errorf("failed to unmarshal %q command data: %w", envelope.Type, err)
    35  		}
    36  	}
    37  
    38  	return cmd, nil
    39  }