Skip to content

Instantly share code, notes, and snippets.

@tangzero
Created January 20, 2016 19:18
Show Gist options
  • Save tangzero/9e298492cc22edd9efe0 to your computer and use it in GitHub Desktop.
Save tangzero/9e298492cc22edd9efe0 to your computer and use it in GitHub Desktop.
Simple HTTP cache proxy
package main
import (
"crypto/md5"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
"github.com/bradfitz/gomemcache/memcache"
"github.com/go-martini/martini"
)
func main() {
serverURL := flag.String("server", "", "Server to be cached: --server htttp://foo.bar.com:1234/")
memcacheURL := flag.String("memcache", "127.0.0.1:11211", "Memcache server: --memcache fake.memcache.server:11211")
flag.Parse()
if *serverURL == "" {
flag.PrintDefaults()
os.Exit(1)
}
m := martini.Classic()
m.Map(memcache.New(*memcacheURL))
m.Get("/**", func(res http.ResponseWriter, req *http.Request, cache *memcache.Client) {
key := fmt.Sprintf("%x", md5.Sum([]byte(req.URL.String())))
fmt.Println(key)
item, err := cache.Get(key)
if err != nil {
fmt.Printf("Cache Error: %v\n", err)
url := fmt.Sprintf("%s%s", *serverURL, req.URL)
fmt.Printf("Calling %s\n", url)
response, err := http.Get(url)
defer response.Body.Close()
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(res, err.Error())
return
}
fmt.Printf("Storing in cache %s\n", req.URL)
content, _ := ioutil.ReadAll(response.Body)
item = &memcache.Item{Key: key, Value: content}
if err := cache.Add(item); err != nil {
fmt.Printf("Cache Error: %v\n", err)
}
} else {
fmt.Printf("Got from cache %s\n", req.URL)
}
res.Header().Set("Content-Type", "application/json")
res.WriteHeader(http.StatusOK)
res.Write(item.Value)
})
m.Run()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment