-
Notifications
You must be signed in to change notification settings - Fork 0
/
telega.go
164 lines (134 loc) · 3.51 KB
/
telega.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
)
func main() {
server := RestController{&Telega{}}
server.Start()
}
///////////////////////
// Model
//////////////////////
type Request struct {
Text string `json:"text"`
}
type Message struct {
ChatId string `json:"chat_id"`
Text string `json:"text"`
}
///////////////////////
// Telegram send
//////////////////////
type ITelega interface {
SendTelegramMessage(message string) ([]byte, error)
}
type Telega struct{}
func (t *Telega) SendTelegramMessage(message string) ([]byte, error) {
token := getEnv("BOT_TOKEN", "")
chatId := getEnv("CHAT_ID", "")
url := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", token)
body := new(bytes.Buffer)
err := json.NewEncoder(body).Encode(Message{chatId, message})
if err != nil {
return nil, err
}
resp, err := http.Post(url, "application/json; charset=utf-8", body)
if err != nil {
return nil, err
}
text, _ := ioutil.ReadAll(resp.Body)
return text, err
}
///////////////////////
// Controller
//////////////////////
type RestController struct {
service ITelega
}
func (this *RestController) Start() {
if useAuth() {
http.HandleFunc("/send", basicAuth(this.SendHandler))
} else {
http.HandleFunc("/send", this.SendHandler)
}
http.HandleFunc("/health", this.HealthHandler)
fmt.Println("Starting server on port:", strings.Split(getPort(), ":")[1])
log.Fatal(http.ListenAndServe(getPort(), nil))
}
func (this *RestController) SendHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Only POST requests are allowed", 400)
return
}
var message Request
err := json.NewDecoder(r.Body).Decode(&message)
if err != nil {
http.Error(w, err.Error(), 400)
return
}
resp, err := this.service.SendTelegramMessage(message.Text)
if err != nil {
http.Error(w, "Message delivery failed: "+err.Error(), 500)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(resp)
}
func (_ *RestController) HealthHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Only GET requests are allowed", 400)
return
}
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("UP"))
}
///////////////////////
// Helper functions
//////////////////////
func useAuth() bool {
_, usernameOk := os.LookupEnv("USERNAME")
_, passwordOk := os.LookupEnv("PASSWORD")
return usernameOk && passwordOk
}
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}
func getPort() string {
var port = getEnv("PORT", "8080")
return ":" + port
}
type handler func(w http.ResponseWriter, r *http.Request)
func basicAuth(pass handler) handler {
return func(w http.ResponseWriter, r *http.Request) {
auth := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
if len(auth) != 2 || auth[0] != "Basic" {
http.Error(w, "authorization failed", http.StatusUnauthorized)
return
}
payload, _ := base64.StdEncoding.DecodeString(auth[1])
pair := strings.SplitN(string(payload), ":", 2)
if len(pair) != 2 || !validateUsernamePassword(pair[0], pair[1]) {
http.Error(w, "authorization failed", http.StatusUnauthorized)
return
}
pass(w, r)
}
}
func validateUsernamePassword(username, password string) bool {
if username == getEnv("USERNAME", "") && password == getEnv("PASSWORD", "") {
return true
}
return false
}