all repos — honk @ 7ed3b24f1a2c7c1d9fed8486ebe3cdb7bf3edb41

my fork of honk

toys/saytheday.go (view raw)

 1package main
 2
 3import (
 4	"flag"
 5	"fmt"
 6	"io/ioutil"
 7	"log"
 8	"net/http"
 9	"net/url"
10	"os"
11	"strings"
12	"time"
13)
14
15func lookandsay(n int) string {
16	s := "1"
17
18	numbers := []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
19	var buf strings.Builder
20	for i := 2; i <= n; i++ {
21		count := 1
22		prev := s[0]
23		for j := 1; j < len(s); j++ {
24			d := s[j]
25			if d == prev {
26				count++
27			} else {
28				buf.WriteString(numbers[count])
29				buf.WriteByte(prev)
30				count = 1
31				prev = d
32			}
33		}
34		buf.WriteString(numbers[count])
35		buf.WriteByte(prev)
36		s = buf.String()
37		buf.Reset()
38	}
39	return s
40}
41
42func honkahonk(server, token, noise string) {
43	form := make(url.Values)
44	form.Add("token", token)
45	form.Add("action", "honk")
46	form.Add("noise", noise)
47	apiurl := fmt.Sprintf("https://%s/api", server)
48	req, err := http.NewRequest("POST", apiurl, strings.NewReader(form.Encode()))
49	if err != nil {
50		log.Fatal(err)
51	}
52	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
53	resp, err := http.DefaultClient.Do(req)
54	if err != nil {
55		log.Fatal(err)
56	}
57	defer resp.Body.Close()
58	answer, err := ioutil.ReadAll(resp.Body)
59	if err != nil {
60		log.Fatal(err)
61	}
62	if resp.StatusCode != 200 {
63		log.Fatalf("status: %d: %s", resp.StatusCode, answer)
64	}
65}
66
67func main() {
68	server := ""
69	token := ""
70	flag.StringVar(&server, "server", server, "server to connnect")
71	flag.StringVar(&token, "token", token, "auth token to use")
72	flag.Parse()
73
74	if server == "" || token == "" {
75		flag.Usage()
76		os.Exit(1)
77	}
78
79	day := time.Now().Day()
80	say := lookandsay(day)
81
82	honkahonk(server, token, say)
83}