-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
90 lines (76 loc) · 2.6 KB
/
main.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/nasermirzaei89/env"
"net/http"
)
type State string
// const (
// StateOK = "ok"
// StatePaused = "paused"
// StateAlerting = "alerting"
// StatePending = "pending"
// StateNoData = "no_data"
//)
type RequestBody struct {
DashboardID int `json:"dashboardId"`
EvalMatches []interface{} `json:"evalMatches"`
ImageURL string `json:"imageUrl"`
Message string `json:"message"`
OrgID int `json:"orgId"`
PanelID int `json:"panelId"`
RuleID int `json:"ruleId"`
RuleName string `json:"ruleName"`
RuleURL string `json:"ruleUrl"`
State State `json:"state"`
Tags map[string]interface{} `json:"tags"`
Title string `json:"title"`
}
const u = "https://rest.nexmo.com/sms/json"
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
var data RequestBody
err := json.NewDecoder(r.Body).Decode(&data)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(map[string]string{"message": "invalid request body", "error": err.Error()})
return
}
text := fmt.Sprintf("%s\n%s", data.Title, data.Message)
body := bytes.NewBufferString(
fmt.Sprintf(
"api_key=%s&api_secret=%s&from=%s&to=%s&text=%s",
env.MustGetString("API_KEY"),
env.MustGetString("API_SECRET"),
env.MustGetString("FROM"),
env.MustGetString("TO"),
text,
),
)
req, err := http.NewRequestWithContext(r.Context(), http.MethodPost, u, body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(map[string]string{"message": "error on new request", "error": err.Error()})
return
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
res, err := http.DefaultClient.Do(req)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(map[string]string{"message": "error on post", "error": err.Error()})
return
}
defer func() { _ = res.Body.Close() }()
if res.StatusCode != http.StatusOK {
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(map[string]string{"message": "error on post status", "error": fmt.Sprintf("response status code is %d", res.StatusCode)})
return
}
})
err := http.ListenAndServe(env.GetString("API_ADDRESS", ":8000"), nil)
if err != nil {
panic(fmt.Errorf("error on listen and serve http: %w", err))
}
}