added log webhook support

This commit is contained in:
2024-03-17 12:07:17 +01:00
parent e0badcb7a2
commit cc745d177d
5 changed files with 96 additions and 4 deletions

View File

@@ -0,0 +1,87 @@
package log2webhook
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
)
type Log struct {
File string `json:"file"`
Function string `json:"func"`
Level string `json:"level"`
Message string `json:"msg"`
Time string `json:"time"`
}
type Message struct {
Embeds []Embed `json:"embeds"`
}
type Embed struct {
Author Author `json:"author"`
Title string `json:"title"`
Description string `json:"description"`
Footer Footer `json:"footer"`
Timestamp string `json:"timestamp"`
}
type Author struct {
Name string `json:"name"`
}
type Footer struct {
Text string `json:"text"`
}
type WebhookWriter struct{}
func (cw *WebhookWriter) Write(p []byte) (n int, err error) {
webhook(p)
return len(p), nil
}
func webhook(p []byte) {
webhookURL := os.Getenv("LOG_WEBHOOK")
if webhookURL == "" || !strings.HasPrefix(webhookURL, "http://") && !strings.HasPrefix(webhookURL, "https://") {
return
}
var logJson Log
json.Unmarshal(p, &logJson)
m := Message{
Embeds: []Embed{
{
Author: Author{
Name: logJson.File,
},
Title: logJson.Function,
Description: logJson.Message,
Footer: Footer{
Text: logJson.Level,
},
Timestamp: logJson.Time,
},
},
}
messageJson, err := json.Marshal(m)
if err != nil {
fmt.Println(err)
return
}
req, err := http.NewRequest("POST", webhookURL, bytes.NewBuffer(messageJson))
if err != nil {
fmt.Println(err)
return
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
}
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
defer resp.Body.Close()
}