package messaging import ( "encoding/json" "fmt" "io" "log" "net/http" "strings" "git.simponic.xyz/simponic/phoneof/utils" ) type HttpSmsMessagingAdapter struct { ApiToken string FromPhoneNumber string ToPhoneNumber string Endpoint string } type HttpSmsMessageData struct { RequestId string `json:"request_id"` } type HttpSmsMessageSendResponse struct { Data HttpSmsMessageData `json:"data"` } func (adapter *HttpSmsMessagingAdapter) encodeMessage(message string) string { requestId := utils.RandomId() return fmt.Sprintf(`{"from":"%s","to":"%s","content":"%s","request_id":"%s"}`, adapter.FromPhoneNumber, adapter.ToPhoneNumber, message, requestId) } func (adapter *HttpSmsMessagingAdapter) SendMessage(message string) (string, error) { url := fmt.Sprintf("%s/v1/messages/send", adapter.Endpoint) payload := strings.NewReader(adapter.encodeMessage(message)) req, _ := http.NewRequest("POST", url, payload) req.Header.Add("x-api-key", adapter.ApiToken) req.Header.Add("Content-Type", "application/json") res, err := http.DefaultClient.Do(req) if err != nil { log.Printf("got err sending message send req %s", err) return "", err } if res.StatusCode/100 != 2 { return "", fmt.Errorf("error sending message: %s %d", message, res.StatusCode) } 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 "", err } return response.Data.RequestId, nil }