Skip to content

Instantly share code, notes, and snippets.

@heymatthew
Created March 20, 2018 06:44
Show Gist options
  • Save heymatthew/4fc5fc4787345458cb0cd0fb313eedf6 to your computer and use it in GitHub Desktop.
Save heymatthew/4fc5fc4787345458cb0cd0fb313eedf6 to your computer and use it in GitHub Desktop.
WIP Counter Webserver
package main
import (
"fmt"
"image"
_ "image/png"
"net/http"
"os"
"regexp"
"sync"
)
var matcher = regexp.MustCompile(`/counter/(\w+)`)
// Handler handles
type Handler struct {
counters map[string]int
mux sync.Mutex
}
func loadImage() {
existingImageFile, err := os.Open("images/numbers.png")
if err != nil {
panic(err)
}
defer existingImageFile.Close()
// TODO use this _ thing, cut it up, and then splat it out to the screen
_, imageType, err := image.Decode(existingImageFile)
fmt.Println("imageType is ", imageType)
}
// ServeHTTP does stuff
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
res := matcher.FindAllStringSubmatch(r.URL.Path, -1)
if res != nil {
lookup := res[0][1]
h.mux.Lock()
defer h.mux.Unlock()
if r.Method == "DELETE" {
h.counters[lookup] = 0
} else {
h.counters[lookup]++
}
fmt.Fprintf(w, "Hello, %d", h.counters[lookup])
return
}
// no pattern matched; send 404 response
http.NotFound(w, r)
}
func main() {
router := Handler{counters: make(map[string]int, 0)}
loadImage()
http.ListenAndServe(":8080", &router)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment