Skip to content

Instantly share code, notes, and snippets.

@bparli
Created March 30, 2020 00:28
Show Gist options
  • Save bparli/a99620565429942433a43fa6d2ccff35 to your computer and use it in GitHub Desktop.
Save bparli/a99620565429942433a43fa6d2ccff35 to your computer and use it in GitHub Desktop.
File server for testing cache performance
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"github.com/bparli/lfuda-go"
)
var (
stats Stats
cache *lfuda.Cache
)
type CacheStats struct {
Stats Stats
Age float64
Size float64
Length int
}
type Stats struct {
Hits int
Misses int
}
func downloadHandler(w http.ResponseWriter, r *http.Request) {
fileName := strings.TrimPrefix(r.URL.Path, "/")
if cache != nil {
if val, ok := cache.Get(fileName); ok {
w.Write(val.([]byte))
stats.Hits++
return
}
}
stats.Misses++
bytes, err := ioutil.ReadFile("/tmp/testCache/" + fileName)
if err != nil {
fmt.Println("Error reading file", fileName, err)
}
if cache != nil {
go func() {
if cache.Set(fileName, bytes) {
fmt.Printf("Setting %s resulted in an eviction\n", fileName)
}
}()
}
w.Write(bytes)
}
func main() {
onEvicted := func(k interface{}, v interface{}) {
if k != v {
fmt.Printf("Evicted key %v\n", k)
}
}
// 100MB cache
cache = lfuda.NewGDSFWithEvict(100*1024*1024, onEvicted)
statsHandler := func(w http.ResponseWriter, _ *http.Request) {
jsonData := &CacheStats{
Stats: stats,
}
if cache != nil {
jsonData = &CacheStats{
Stats: stats,
Age: cache.Age(),
Size: cache.Size(),
Length: cache.Len(),
}
}
data, err := json.Marshal(jsonData)
if err != nil {
fmt.Println("Error marshaling the response", err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(data)
}
http.HandleFunc("/stats", statsHandler)
http.HandleFunc("/", downloadHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment