Skip to content

Instantly share code, notes, and snippets.

@syphoxy
Last active March 1, 2018 20:21
Show Gist options
  • Save syphoxy/af3ab3a785ffb2efe142f2fcb831be0c to your computer and use it in GitHub Desktop.
Save syphoxy/af3ab3a785ffb2efe142f2fcb831be0c to your computer and use it in GitHub Desktop.
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"strings"
"time"
)
type SunRiseSetResponse struct {
Results struct {
Sunrise time.Time `json:"sunrise"`
Sunset time.Time `json:"sunset"`
SolarNoon time.Time `json:"solar_noon"`
DayLength time.Duration `json:"day_length"`
CivilTwilightBegin time.Time `json:"civil_twilight_begin"`
CivilTwilightEnd time.Time `json:"civil_twilight_end"`
NauticalTwilightBegin time.Time `json:"nautical_twilight_begin"`
NauticalTwilightEnd time.Time `json:"nautical_twilight_end"`
AstronomicalTwilightBegin time.Time `json:"astronomical_twilight_begin"`
AstronomicalTwilightEnd time.Time `json:"astronomical_twilight_end"`
} `json:"results"`
Status string `json:"status"`
}
func main() {
lat := flag.Float64("lat", 0, "latitude")
lng := flag.Float64("lng", 0, "longitude")
socket := flag.String("unix-socket", os.Getenv("HOME")+"/.wego-server.sock", "unix socket path")
flag.Parse()
client := http.Client{
Transport: &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", *socket)
},
},
}
for {
url := fmt.Sprintf("https://api.sunrise-sunset.org/json?lat=%f&lng=%f&formatted=0", *lat, *lng)
resp, err := http.Get(url)
if err != nil {
log.Println(err)
continue
}
defer resp.Body.Close()
response := SunRiseSetResponse{}
err = json.NewDecoder(resp.Body).Decode(&response)
if err != nil && err != io.EOF {
log.Println(err)
continue
}
wait := time.Until(response.Results.Sunset)
if wait < 0 {
wait := time.Minute * 5
log.Println("time is in the past, sleeping for", wait)
time.Sleep(wait)
continue
}
log.Println("sleeping for", wait)
time.Sleep(wait)
client.Post("http://unix/socket", "application/x-www-form-urlencoded", strings.NewReader("state=1"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment