serve up a cached version of http://xkcd.com/1335/ http://xkcd.com/1335/

main.go 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package main
  2. import (
  3. "bytes"
  4. "flag"
  5. "fmt"
  6. "image"
  7. "image/color"
  8. "image/png"
  9. "log"
  10. "net/http"
  11. "os"
  12. "sync"
  13. "time"
  14. )
  15. var port = flag.Int("port", 8000, "port")
  16. type Now struct {
  17. lastUpdated time.Time
  18. cacheWindow time.Duration
  19. buffer *bytes.Buffer
  20. lock sync.RWMutex
  21. }
  22. func NewNow(d time.Duration) *Now {
  23. return &Now{
  24. cacheWindow: d,
  25. buffer: &bytes.Buffer{},
  26. }
  27. }
  28. func (n *Now) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  29. log.Printf("%+v", req.RemoteAddr)
  30. if time.Now().After(n.lastUpdated.Add(n.cacheWindow)) {
  31. log.Println("updating image")
  32. n.Update()
  33. n.lastUpdated = time.Now()
  34. }
  35. n.lock.RLock()
  36. w.Write(n.buffer.Bytes())
  37. n.lock.RUnlock()
  38. }
  39. func (n *Now) Update() {
  40. resp, err := http.Get("http://imgs.xkcd.com/comics/now.png")
  41. if err != nil {
  42. log.Fatal(err)
  43. }
  44. defer resp.Body.Close()
  45. src, err := png.Decode(resp.Body)
  46. if err != nil {
  47. log.Fatal(err)
  48. }
  49. bounds := src.Bounds()
  50. dest := image.NewNRGBA(bounds)
  51. for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
  52. for x := bounds.Min.X; x < bounds.Max.X; x++ {
  53. r, g, b, _ := src.At(x, y).RGBA()
  54. if r == 0xFFFF && g == 0xFFFF && b == 0xFFFF {
  55. dest.Set(x, y, color.NRGBA{0, 0, 0, 0})
  56. } else {
  57. dest.Set(x, y, src.At(x, y))
  58. }
  59. }
  60. }
  61. n.lock.Lock()
  62. png.Encode(n.buffer, dest)
  63. n.lock.Unlock()
  64. }
  65. func main() {
  66. flag.Parse()
  67. hostname, err := os.Hostname()
  68. if err != nil {
  69. log.Fatal("problem getting hostname:", err)
  70. }
  71. log.Printf("serving on: http://%s:%d/", hostname, *port)
  72. addr := fmt.Sprintf(":%d", *port)
  73. http.Handle("/", NewNow(15*time.Minute))
  74. err = http.ListenAndServe(addr, nil)
  75. if err != nil {
  76. log.Fatal(err)
  77. }
  78. }