github.com/vnforks/kid/v5@v5.22.1-0.20200408055009-b89d99c65676/model/command_response.go (about)

     1  // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
     2  // See LICENSE.txt for license information.
     3  
     4  package model
     5  
     6  import (
     7  	"encoding/json"
     8  	"io"
     9  	"io/ioutil"
    10  	"strings"
    11  
    12  	"github.com/vnforks/kid/v5/utils/jsonutils"
    13  )
    14  
    15  const (
    16  	COMMAND_RESPONSE_TYPE_IN_CLASS  = "in_class"
    17  	COMMAND_RESPONSE_TYPE_EPHEMERAL = "ephemeral"
    18  )
    19  
    20  type CommandResponse struct {
    21  	ResponseType     string             `json:"response_type"`
    22  	Text             string             `json:"text"`
    23  	Username         string             `json:"username"`
    24  	ClassId          string             `json:"class_id"`
    25  	IconURL          string             `json:"icon_url"`
    26  	Type             string             `json:"type"`
    27  	Props            StringInterface    `json:"props"`
    28  	GotoLocation     string             `json:"goto_location"`
    29  	TriggerId        string             `json:"trigger_id"`
    30  	SkipSlackParsing bool               `json:"skip_slack_parsing"` // Set to `true` to skip the Slack-compatibility handling of Text.
    31  	ExtraResponses   []*CommandResponse `json:"extra_responses"`
    32  }
    33  
    34  func (o *CommandResponse) ToJson() string {
    35  	b, _ := json.Marshal(o)
    36  	return string(b)
    37  }
    38  
    39  func CommandResponseFromHTTPBody(contentType string, body io.Reader) (*CommandResponse, error) {
    40  	if strings.TrimSpace(strings.Split(contentType, ";")[0]) == "application/json" {
    41  		return CommandResponseFromJson(body)
    42  	}
    43  	if b, err := ioutil.ReadAll(body); err == nil {
    44  		return CommandResponseFromPlainText(string(b)), nil
    45  	}
    46  	return nil, nil
    47  }
    48  
    49  func CommandResponseFromPlainText(text string) *CommandResponse {
    50  	return &CommandResponse{
    51  		Text: text,
    52  	}
    53  }
    54  
    55  func CommandResponseFromJson(data io.Reader) (*CommandResponse, error) {
    56  	b, err := ioutil.ReadAll(data)
    57  	if err != nil {
    58  		return nil, err
    59  	}
    60  
    61  	var o CommandResponse
    62  	err = json.Unmarshal(b, &o)
    63  	if err != nil {
    64  		return nil, jsonutils.HumanizeJsonError(err, b)
    65  	}
    66  
    67  	return &o, nil
    68  }