Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module github.com/rakadityas/cache-in-go

go 1.14

require github.com/coocood/freecache v1.1.1
8 changes: 8 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko=
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
github.com/coocood/freecache v1.1.1 h1:uukNF7QKCZEdZ9gAV7WQzvh0SbjwdMF6m3x3rxEkaPc=
github.com/coocood/freecache v1.1.1/go.mod h1:OKrEjkGVoxZhyWAJoeFi5BMLUJm2Tit0kpGkIr7NGYY=
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72 h1:qLC7fQah7D6K1B0ujays3HV9gkFtllcxhzImRR7ArPQ=
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
62 changes: 62 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,88 @@ package main

import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"

"github.com/coocood/freecache"
)

var cache *freecache.Cache

func github(w http.ResponseWriter, r *http.Request) {

cacheVal, err := getCache([]byte("status"))
if err != nil {
json.NewEncoder(w).Encode(err)
}

if len(cacheVal) != 0 {
json.NewEncoder(w).Encode(string(cacheVal))
return
}

resp, err := http.Get("https://api.github.com/status")
if err != nil {
json.NewEncoder(w).Encode(err)
}
data, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()

err = saveCache([]byte("status"), data, 10)
if err != nil {
json.NewEncoder(w).Encode(err)
return
}

json.NewEncoder(w).Encode(string(data))
}

func initCache() {
cache = freecache.NewCache(10 * 1024 * 1024)
}

func saveCache(key []byte, value []byte, expireSeconds int) (err error) {
fmt.Println("[SAVE CACHE]")
return cache.Set(key, value, expireSeconds)
}

func getCache(key []byte) ([]byte, error) {
fmt.Println("[GET CACHE]")
return cache.Get(key)
}

func handleRequests() {
http.HandleFunc("/github", github)
log.Fatal(http.ListenAndServe(":10000", nil))
}

func main() {

initCache()

handleRequests()
}

/**
-. data apa yg dibalikin
curl --location --request GET 'localhost:10000/github'

pola data:
- response
- "{\"message\":\"GitHub lives! (2020-10-09 02:06:14 -0700) (1)\"}"

- berubah per 10 detik
- balikan satu response (general)

-. cache yang mana
- freecache

- keynya by apa
- public key

-. kenapa pilih cache itu
-

**/