1 回答
TA贡献1884条经验 获得超4个赞
以下代码是此请求的解决方案。
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"time"
"log"
"strconv"
)
//DataFeed contains data for the string concatenation
type DataFeed struct {
CustomerID int
CustomerName string
CustomerEmail string
CustomerPhone string
Received time.Time
}
//ConcatenateDate takes data from DataFeed and concatenates them into a msg ('\n' separated)
func ConcatenateData(d DataFeed) (msg string) {
values := []string{}
values = append(values, "New notification incoming, see more details below:")
values = append(values, "ID: " + strconv.Itoa(d.CustomerID))
values = append(values, "Name: " + d.CustomerName)
values = append(values, "Email: " + d.CustomerEmail)
values = append(values, "Phone Number: " + d.CustomerPhone)
values = append(values, "Received: " + (d.Received).String())
msg = strings.Join(values, "\n")
//fmt.Println(values)
//fmt.Println(msg)
return msg
}
// SlackRequestBody comment here
type SlackRequestBody struct {
Text string `json:"text"`
}
func SendSlackNotification(webhookURL string, msg string) error {
slackBody, _ := json.Marshal(SlackRequestBody{Text: msg})
req, err := http.NewRequest(http.MethodPost, webhookURL, bytes.NewBuffer(slackBody))
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/json")
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return err
}
buf := new(bytes.Buffer)
buf.ReadFrom(resp.Body)
if buf.String() != "ok" {
return errors.New("Non-ok response returned from Slack")
}
return nil
}
func main() {
webhookURL := "https://hooks.slack.com/services/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"
e := DataFeed{
CustomerID: 767,
CustomerName: "Tom",
CustomerEmail: "tom.nemeth85@gmail.com",
CustomerPhone: "07479551111",
Received: time.Now(),
}
fmt.Println(e)
fmt.Printf("\n")
fmt.Println(ConcatenateData(e))
err := SendSlackNotification(webhookURL, ConcatenateData(e)) //--> Set "e" as argument here
if err != nil {
log.Fatal(err)
}
- 1 回答
- 0 关注
- 76 浏览
添加回答
举报