-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
111 lines (95 loc) · 2.31 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package main
import (
"flag"
"fmt"
"log"
"net/http"
"sync"
"text/template"
"time"
)
// Command-line flags.
var (
httpAddr = flag.String("http", ":8080", "Listen address")
pollPeriod = flag.Duration("poll", 5*time.Second, "Poll period")
version = flag.String("version", "1.4", "Go version")
)
const baseChangeURL = "http://code.google.com/p/go/source/detail?r="
func main() {
flag.Parse()
changeURL := fmt.Sprintf("%sgo%s", baseChangeURL, *version)
http.Handle("/", NewServer(*version, changeURL, *pollPeriod))
log.Fatal(http.ListenAndServe(*httpAddr, nil))
}
// Server implements the outyet server.
// It serves the user interface (it's an http.Handler)
// and polls the remote repository for changes.
type Server struct {
version string
url string
period time.Duration
//shared
mu sync.RWMutex
yes bool
}
// NewServer returns an intiated outyet server.
func NewServer(version, url string, period time.Duration) *Server {
s := &Server{version: version, url: url, period: period}
go s.poll() // this makes the program concurrent.
return s
}
// poll polls the change URL for the specified period until the tag exists.
// Then it sets the Server's yes field true and exits
func (s *Server) poll() {
for !isTagged(s.url) {
pollSleep(s.period)
}
s.mu.Lock()
s.yes = true
s.mu.Unlock()
pollDone()
}
// stop relying on `sleep` and stub out the `sleep` (so i can swap out at test)
var (
pollSleep = time.Sleep
pollDone = func() {} // noop (no operation)
)
// isTagged makes an HTTP HEAD request to the given URL and reports whether it
// returned a 200 OK response.
func isTagged(url string) bool {
header, err := http.Head(url)
if err != nil {
log.Print(err)
return false
}
return header.StatusCode == http.StatusOK
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.mu.RLock()
data := struct {
Url string
Version string
Yes bool
}{
s.url,
s.version,
s.yes,
}
s.mu.RUnlock()
if err := tmpl.Execute(w, data); err != nil {
log.Print(err)
}
}
// tmpl is the HTML template that drives the user interface.
var tmpl = template.Must(template.New("tmpl").Parse(`
<!DOCTYPE html><html><body><center>
<h2>Is Go {{.Version}} out yet?</h2>
<h1>
{{if .Yes}}
<a href="{{.Url}}">YES!</a>
{{else}}
No. :-(
{{end}}
</h1>
</center></body></html>
`))