Skip to content

Instantly share code, notes, and snippets.

@elbuo8
Created January 8, 2014 02:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elbuo8/8310736 to your computer and use it in GitHub Desktop.
Save elbuo8/8310736 to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/sendgrid/sendgrid-go"
"log"
"net/http"
"os"
)
type Item struct {
Title string
URL string
LinkScore int `json:"score"`
}
type Response struct {
Data struct {
Children []struct {
Data Item
}
}
}
func Get(reddit string) ([]Item, error) {
url := fmt.Sprintf("http://reddit.com/r/%s.json", reddit)
r, err := http.Get(url)
if err != nil {
return nil, err
}
defer r.Body.Close()
if r.StatusCode != http.StatusOK {
return nil, errors.New(r.Status)
}
resp := new(Response)
err = json.NewDecoder(r.Body).Decode(resp)
if err != nil {
return nil, err
}
items := make([]Item, len(resp.Data.Children))
for i, child := range resp.Data.Children {
items[i] = child.Data
}
return items, nil
}
func (i Item) String() string {
com := ""
switch i.LinkScore {
case 0:
// nothing
case 1:
com = " Score: 1"
default:
com = fmt.Sprintf(" (Score: %d)", i.LinkScore)
}
return fmt.Sprintf("%s%s\n <a href=\"%s\">%s</a>", i.Title, com, i.URL, i.URL)
}
func Email() string {
var buffer bytes.Buffer
items, err := Get("golang")
if err != nil {
log.Fatal(err)
}
//needed to build string
for _, item := range items {
buffer.WriteString(item.String())
}
//fmt.Println(item)
return buffer.String()
}
func main() {
sg := sendgrid.NewSendGridClient(os.Getenv("SG_USER"), os.Getenv("SG_PWD"))
message := sendgrid.NewMail()
message.AddTo("yamil@sendgrid.com")
message.AddToName("Robin J")
message.AddSubject("SendGrid Testing")
message.AddFrom("rbin@sendgrid.com")
message.AddHTML(Email())
if r := sg.Send(message); r == nil {
fmt.Println("Email sent!")
} else {
fmt.Println(r)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment