-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTwilio_poc_main.go
89 lines (75 loc) · 2.3 KB
/
Twilio_poc_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
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"strings"
//"io/ioutil"
"log"
"github.com/gorilla/mux"
)
type sendMessageRequest struct {
Message string `json:"message"`
To string `json:"to"`
}
type response struct {
Status string `json:"status"`
StatusText string `json:"statusText"`
}
func homeLink(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome sms sending service!")
}
func sendSms(w http.ResponseWriter, r *http.Request) {
//Twilio credentials
accountSid := "AC0e9c4ba71a13276c2d05018fb452fff6"
authToken := "c248ed0ab16317542bf12475058fc8e9"
urlStr := "https://api.twilio.com/2010-04-01/Accounts/" + accountSid + "/Messages.json"
fromPhoneNumber := "+17867892028"
var smsReq sendMessageRequest
err := json.NewDecoder(r.Body).Decode(&smsReq)
if err != nil {
fmt.Fprintf(w, "Kindly enter valid data to send sms")
}
fmt.Printf("Client Request: %+v", smsReq)
//Fetching sms data from sms send request
msgData := url.Values{}
msgData.Set("To", smsReq.To)
msgData.Set("From", fromPhoneNumber)
msgData.Set("Body", smsReq.Message)
msgDataReader := *strings.NewReader(msgData.Encode())
client := &http.Client{}
req, _ := http.NewRequest("POST", urlStr, &msgDataReader)
req.SetBasicAuth(accountSid, authToken)
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
fmt.Println("Request to be sent to Twilio: ", req)
var resp1 response
resp, _ := client.Do(req)
fmt.Println("Twilio Response: ", resp)
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
var data map[string]interface{}
decoder := json.NewDecoder(resp.Body)
err := decoder.Decode(&data)
if err == nil {
fmt.Println(data["sid"])
resp1 = response{Status: "Success", StatusText: "SMS Sent!"}
w.WriteHeader(http.StatusOK)
}
} else {
fmt.Println(resp.Status)
resp1 = response{Status: "Failed", StatusText: resp.Status}
w.WriteHeader(resp.StatusCode)
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp1)
}
func main() {
dbPass := os.Getenv("DATABASE_PASS")
fmt.Println("ENV: ", dbPass)
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", homeLink)
router.HandleFunc("/sendsms", sendSms).Methods("POST")
log.Fatal(http.ListenAndServe(":8080", router))
}