Skip to content

Instantly share code, notes, and snippets.

@s4l1h
Created October 16, 2016 14:11
Show Gist options
  • Save s4l1h/e841ce9c655b6f81b31ebd8bba9a048b to your computer and use it in GitHub Desktop.
Save s4l1h/e841ce9c655b6f81b31ebd8bba9a048b to your computer and use it in GitHub Desktop.
package main
import (
"errors"
"fmt"
)
// Cache interface
type Cache interface {
// Name cache provider adını döndürecek
Name() string
// Set cache'e data kaydeder
Set(key string, data []byte) error
// Get cache'ten data alır
Get(key string) ([]byte, error)
}
var (
errorNotFound = errors.New("Cache Datası Bulunamadı: ")
errorEmptyKey = errors.New("Key Boş Olamaz")
)
// MemoryCache In memory'de data saklama sınıfı
type MemoryCache struct {
data map[string][]byte
}
// NewMemoryCache Yeni bir memory cache oluşturur
func NewMemoryCache() Cache {
return &MemoryCache{data: make(map[string][]byte)}
}
// Name : Cache Provider Adını döndürür
func (c *MemoryCache) Name() string {
return "MemoryCache"
}
// Get : İn Memory'de tutulan datayı alır.
func (c *MemoryCache) Get(key string) ([]byte, error) {
if value, oke := c.data[key]; oke == true {
return value, nil
}
return []byte(""), errorNotFound
}
// Set : İn Memorye datayı kaydeder
func (c *MemoryCache) Set(key string, data []byte) error {
if key == "" {
return errorEmptyKey
}
c.data[key] = data
return nil
}
func main() {
var cache Cache
cache = NewMemoryCache()
fmt.Println("Cache Provider : ", cache.Name())
if err := cache.Set("twitter", []byte("s4l1h")); err != nil {
fmt.Println("Hata Oluştu : ", err)
return
}
value, err := cache.Get("twitter")
if err != nil {
fmt.Println("Hata Oluştu : ", err)
return
}
fmt.Println(string(value)) // Çekilen Byte tipindeki datayı string'e çevirelim
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment