github.com/artisanhe/tools@v1.0.1-0.20210607022958-19a8fef2eb04/catgo/cat-go/message/message.go (about)

     1  package message
     2  
     3  import (
     4  	"bytes"
     5  	"time"
     6  )
     7  
     8  const (
     9  	CatSuccess = "0"
    10  	CatError   = "-1"
    11  )
    12  
    13  type Flush func(m Messager)
    14  
    15  //noinspection GoNameStartsWithPackageName
    16  type MessageGetter interface {
    17  	GetType() string
    18  	GetName() string
    19  	GetStatus() string
    20  	GetData() *bytes.Buffer
    21  	GetTime() time.Time
    22  }
    23  
    24  type Messager interface {
    25  	MessageGetter
    26  	AddData(k string, v ...string)
    27  	SetData(v string)
    28  	SetStatus(status string)
    29  	SetTime(time time.Time)
    30  	Complete()
    31  }
    32  
    33  type Message struct {
    34  	Type   string
    35  	Name   string
    36  	Status string
    37  
    38  	timestamp time.Time
    39  
    40  	data *bytes.Buffer
    41  
    42  	flush Flush
    43  }
    44  
    45  func NewMessage(mtype, name string, flush Flush) Message {
    46  	return Message{
    47  		Type:      mtype,
    48  		Name:      name,
    49  		Status:    CatSuccess,
    50  		timestamp: time.Now(),
    51  		data:      new(bytes.Buffer),
    52  		flush:     flush,
    53  	}
    54  }
    55  
    56  func (m *Message) Complete() {
    57  	if m.flush != nil {
    58  		m.flush(m)
    59  	}
    60  }
    61  
    62  func (m *Message) GetType() string {
    63  	return m.Type
    64  }
    65  
    66  func (m *Message) GetName() string {
    67  	return m.Name
    68  }
    69  
    70  func (m *Message) GetStatus() string {
    71  	return m.Status
    72  }
    73  
    74  func (m *Message) GetData() *bytes.Buffer {
    75  	return m.data
    76  }
    77  
    78  func (m *Message) GetTime() time.Time {
    79  	return m.timestamp
    80  }
    81  
    82  func (m *Message) SetTime(t time.Time) {
    83  	m.timestamp = t
    84  }
    85  
    86  func (m *Message) AddData(k string, v ...string) {
    87  	if m.data.Len() != 0 {
    88  		m.data.WriteRune('&')
    89  	}
    90  	if len(v) == 0 {
    91  		m.data.WriteString(k)
    92  	} else {
    93  		m.data.WriteString(k)
    94  		m.data.WriteRune('=')
    95  		m.data.WriteString(v[0])
    96  	}
    97  }
    98  
    99  func (m *Message) SetData(v string) {
   100  	m.data.Reset()
   101  	m.data.WriteString(v)
   102  }
   103  
   104  func (m *Message) SetStatus(status string) {
   105  	m.Status = status
   106  }
   107  
   108  func (m *Message) SetSuccessStatus() {
   109  	m.Status = CatSuccess
   110  }