Created
April 17, 2015 17:52
-
-
Save gedex/a5b8379a4022e47b34f0 to your computer and use it in GitHub Desktop.
HTTP server that increments counter and serves the page with the counter rendered. Useful for verification if you've component that fetch external content with TTL.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"log" | |
"net/http" | |
"time" | |
) | |
var ( | |
listen = flag.String("listen", ":8080", "HTTP listen address") | |
interval = flag.Duration("interval", time.Minute, "Interval to update the counter") | |
counter = 0 | |
) | |
func main() { | |
flag.Parse() | |
// Update counter. | |
every(*interval, incrementCounter) | |
// HTTP handlers. | |
http.HandleFunc("/", handler) | |
log.Printf("Starting server %s\n", *listen) | |
log.Fatal(http.ListenAndServe(*listen, nil)) | |
} | |
func handler(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintf(w, "<h1>Counter: %d</h1>", counter) | |
} | |
func every(dur time.Duration, fn func()) { | |
time.AfterFunc(dur, func() { | |
fn() | |
every(dur, fn) | |
}) | |
} | |
func incrementCounter() { | |
counter += 1 | |
log.Printf("Counter incremented by one, its value now: %d\n", counter) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment