phoneof/adapters/messaging/http_sms.go

54 lines
1.4 KiB
Go
Raw Normal View History

2025-01-03 01:47:07 -08:00
package messaging
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"strings"
"git.simponic.xyz/simponic/phoneof/utils"
)
type HttpSmsMessageData struct {
RequestId string `json:"request_id"`
}
type HttpSmsMessageSendResponse struct {
Data HttpSmsMessageData `json:"data"`
}
2025-01-05 15:16:26 -08:00
func HttpSmsContinuation(apiToken string, fromPhoneNumber string, toPhoneNumber string, httpSmsEndpoint string) Continuation {
return func(message Message) ContinuationChain {
encodedMsg := fmt.Sprintf(`{"from":"%s","to":"%s","content":"%s"}`, fromPhoneNumber, toPhoneNumber, utils.Quote(message.Encode()))
log.Println(encodedMsg)
return func(success Continuation, failure Continuation) ContinuationChain {
url := fmt.Sprintf("%s/v1/messages/send", httpSmsEndpoint)
payload := strings.NewReader(encodedMsg)
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("x-api-key", apiToken)
req.Header.Add("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil || res.StatusCode/100 != 2 {
log.Printf("got err sending message send req %s %v %s", message, res, err)
return failure(message)
}
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
var response HttpSmsMessageSendResponse
err = json.Unmarshal(body, &response)
if err != nil {
log.Printf("got error unmarshaling response: %s %s", body, err)
return failure(message)
}
return success(message)
}
2025-01-03 01:47:07 -08:00
}
}