github.com/astaxie/beego@v1.12.3/logs/jianliao.go (about)

     1  package logs
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"net/http"
     7  	"net/url"
     8  	"time"
     9  )
    10  
    11  // JLWriter implements beego LoggerInterface and is used to send jiaoliao webhook
    12  type JLWriter struct {
    13  	AuthorName  string `json:"authorname"`
    14  	Title       string `json:"title"`
    15  	WebhookURL  string `json:"webhookurl"`
    16  	RedirectURL string `json:"redirecturl,omitempty"`
    17  	ImageURL    string `json:"imageurl,omitempty"`
    18  	Level       int    `json:"level"`
    19  }
    20  
    21  // newJLWriter create jiaoliao writer.
    22  func newJLWriter() Logger {
    23  	return &JLWriter{Level: LevelTrace}
    24  }
    25  
    26  // Init JLWriter with json config string
    27  func (s *JLWriter) Init(jsonconfig string) error {
    28  	return json.Unmarshal([]byte(jsonconfig), s)
    29  }
    30  
    31  // WriteMsg write message in smtp writer.
    32  // it will send an email with subject and only this message.
    33  func (s *JLWriter) WriteMsg(when time.Time, msg string, level int) error {
    34  	if level > s.Level {
    35  		return nil
    36  	}
    37  
    38  	text := fmt.Sprintf("%s %s", when.Format("2006-01-02 15:04:05"), msg)
    39  
    40  	form := url.Values{}
    41  	form.Add("authorName", s.AuthorName)
    42  	form.Add("title", s.Title)
    43  	form.Add("text", text)
    44  	if s.RedirectURL != "" {
    45  		form.Add("redirectUrl", s.RedirectURL)
    46  	}
    47  	if s.ImageURL != "" {
    48  		form.Add("imageUrl", s.ImageURL)
    49  	}
    50  
    51  	resp, err := http.PostForm(s.WebhookURL, form)
    52  	if err != nil {
    53  		return err
    54  	}
    55  	defer resp.Body.Close()
    56  	if resp.StatusCode != http.StatusOK {
    57  		return fmt.Errorf("Post webhook failed %s %d", resp.Status, resp.StatusCode)
    58  	}
    59  	return nil
    60  }
    61  
    62  // Flush implementing method. empty.
    63  func (s *JLWriter) Flush() {
    64  }
    65  
    66  // Destroy implementing method. empty.
    67  func (s *JLWriter) Destroy() {
    68  }
    69  
    70  func init() {
    71  	Register(AdapterJianLiao, newJLWriter)
    72  }