package msgdata import ( "encoding/json" "errors" "fmt" "strings" ) type CommandRequest interface { Data() RequestData Attributes() RequestAttributes } type GeneralAttributes struct { BannerID string `json:"bannerId"` StoreID string `json:"storeId"` TerminalID string `json:"terminalId"` SessionID string `json:"sessionId"` Identity string `json:"identity"` Version string `json:"version"` Signature string `json:"signature"` } func newGeneralAttributes(psAttr map[string]string) (attr *GeneralAttributes, err error) { if psAttr == nil { return nil, fmt.Errorf("received nil map") } bytes, err := json.Marshal(psAttr) if err != nil { return nil, fmt.Errorf("unmarshaling Attributes: %w", err) } err = json.Unmarshal(bytes, &attr) if err != nil { return nil, fmt.Errorf("unmarshaling Attributes: %w", err) } return attr, nil } func (attr *GeneralAttributes) validate(errs []error) []error { if attr.BannerID == "" { errs = append(errs, errors.New("attributes missing banner ID")) } if attr.StoreID == "" { errs = append(errs, errors.New("attributes missing store ID")) } if attr.TerminalID == "" { errs = append(errs, errors.New("attributes missing terminal ID")) } if attr.SessionID == "" { errs = append(errs, errors.New("attributes missing session ID")) } if attr.Identity == "" { errs = append(errs, errors.New("attributes missing identity")) } return errs } type RequestData struct { Command string `json:"command"` } type commandRequest struct { data RequestData attributes RequestAttributes } func (req *commandRequest) Data() RequestData { data := req.data return data } func (req *commandRequest) Attributes() RequestAttributes { attr := req.attributes return attr } func NewCommandRequest(command string, attrmap map[string]string) (CommandRequest, error) { data := RequestData{ Command: command, } attr, err := newGeneralAttributes(attrmap) if err != nil { return nil, err } req := &commandRequest{data: data, attributes: RequestAttributes{GeneralAttributes: *attr, CommandID: attrmap["commandId"]}} if err = req.validate(); err != nil { return nil, err } return req, nil } type CommandRequestErr []error func (myerr CommandRequestErr) Error() string { var msg []string for _, err := range myerr { msg = append(msg, err.Error()) } return strings.Join(msg, ", ") } func (req *commandRequest) validate() error { errs := CommandRequestErr{} if req.data.Command == "" { errs = append(errs, errors.New("request missing command")) } if req.attributes.CommandID == "" { errs = append(errs, errors.New("request missing command id")) } errs = req.attributes.validate(errs) if len(errs) != 0 { return errs } return nil }