Skip to content

Instantly share code, notes, and snippets.

@Narsil
Last active December 27, 2015 08:59
Show Gist options
  • Save Narsil/7300473 to your computer and use it in GitHub Desktop.
Save Narsil/7300473 to your computer and use it in GitHub Desktop.
package main
import (
"time"
"net/http"
"net/smtp"
"fmt"
)
func sendMail(body string) error{
// Set up authentication information.
// Connect to the server, authenticate, set the sender and recipient,
// and send the email all in one step.
addr := "smtp.gmail.com:587"
c, err := smtp.Dial(addr)
if err != nil {
return err
}
///////////////////////
// Not present in std pkg. Bug ??
defer c.Quit()
///////////////////////
if err := c.Hello(""); err != nil {
return err
}
if ok, _ := c.Extension("STARTTLS"); ok {
if err = c.StartTLS(nil); err != nil {
return err
}
}
a := smtp.PlainAuth(
"",
"[email protected]",
"password",
"smtp.gmail.com",
)
if err = c.Auth(a); err != nil {
return err
}
from := "[email protected]"
to := []string{"[email protected]"}
subject := body
msg := fmt.Sprint("Subject: ", subject, "\r\n\r\n", body)
if err = c.Mail(from); err != nil {
return err
}
for _, addr := range to {
if err = c.Rcpt(addr); err != nil {
return err
}
}
w, err := c.Data()
if err != nil {
return err
}
_, err = w.Write([]byte(msg))
if err != nil {
return err
}
err = w.Close()
if err != nil {
return err
}
fmt.Println("Send mail")
return nil
}
func ping(url string, c chan *http.Response, start_pinging, exit chan bool){
for _ = range(start_pinging){
fmt.Println("Pinging ", url)
start := time.Now()
resp, err := http.Get(url)
stop := time.Now()
if stop.Sub(start) < time.Millisecond{
exit <- true
}
fmt.Println("Received ", url, stop.Sub(start))
if err != nil{
err = sendMail(fmt.Sprint("Error fetching ", url, " error: ", err))
if err != nil{
fmt.Println("Error sending mail", err)
}
}else{
select{
case c<-resp:
default:
}
}
}
}
func main(){
responses := make(chan *http.Response)
exit := make(chan bool)
url := "SOME URL"
err := sendMail(fmt.Sprint("Starting pinging :", url))
if err != nil{
fmt.Println("Error sending mail", err)
}
start_pinging := make(chan bool)
go ping(url, responses, start_pinging, exit)
for _ = range time.Tick(60 * time.Second) {
fmt.Println("Tick")
start_pinging<-true
select {
case resp := <-responses:
if resp.StatusCode != 200{
err = sendMail(fmt.Sprint("Error fetching ", url, " (non 200 code, actual:", resp.StatusCode, ")"))
if err != nil{
fmt.Println("Error sending mail", err)
}
}else{
fmt.Print(".")
}
case <-time.After(2 * time.Second):
err = sendMail(fmt.Sprint("Error fetching ", url, " (timeout)"))
if err != nil{
fmt.Println("Error sending mail", err)
}
case <- exit:
return
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment