Hey,
New to Go, and decided to build a slack bot which interacts with a meme generator site such as imgflip to post a meme with top and bottom text specified such as '/meme badLuckBrian, top text, bottom_text'.
I'm fine with most of it and have individual bits working but I'm struggling with structuring the JSON correctly in my request to the Slack webhook when posting attachments - an array of hashes. So I can get it posting the a message to Slack but not an attachment (in Go that is; I have used the API successfully via Curl and Ruby).
See below and http://play.golang.org/p/W9A3LQ0QCf to see my issue.
Currently returning {"text":"foo","username":"baz","channel":"bar","attachments":"[{'image_url': 'http://i.imgflip.com/1bij.jpg'}]"}
Need to return {"text":"foo","username":"baz","channel":"bar","attachments":[{'image_url': 'http://i.imgflip.com/1bij.jpg'}]}
The obvious issue here is Attachment is a string, but I am unsure of what data type I should be using in the struct, or whether my approach is correct at all.
Like I said, new to Go and just picking up things I've seen in GitHub repos.
Advice appreciated. Count me as a noob.
Cheers, Adam.
EDIT
Thanks everyone for the help. Went with the approach of treating Attachment as it's own struct as Slack Attachments can have other attributes than image_url.
Cheers! Adam.
评论:
mwholt:
drummeradam89:< shameless plug for https://mholt.github.io/json-to-go/ >
alexwhoizzle:Aha! Shameless plug accepted - this really helps. Cheers!
mwholt:Do you know of something like this for csv files? If not then I might try to make of port of json-to-go for csv.
Really liking caddy too!
uncle_bad_touches:Hmmm, I don't, but that's a cool idea. I recommend using Papa Parse for parsing the CSV sample. (There I go again - another shameless plug!)
(Thanks for your comment, by the way - glad you like it.)
jayposs:Try this: http://play.golang.org/p/cTHMaYLyhY
jasonrichardsmith:This solution should work as well.
type attachment struct { ImageUrl string `json:"image_url"` } type slackMessage struct { Text string `json:"text"` Username string `json:"username"` Channel string `json:"channel"` Attachments []attachment `json:"attachments"` } slackAttachments := make([]attachment, cnt) // cnt = # of attachments // if you have an array (slice) of url's, use a for loop slackAttachments = append(slackAttachments, attachment{"url1"}) slackAttachments = append(slackAttachments, attachment{"url2"}) set payload slackMessage.Attachments = slackAttachments
drummeradam89:Depending on your use case I would make it more expressive. http://play.golang.org/p/K4BST_Pm2k
This works well for this use case as there are other attributes to an attachment that could be used. Cheers!