main.go

  1. package main
  2. import (
  3. "mycache/cache"
  4. "mycache/http"
  5. )
  6. func main() {
  7. c := cache.New("inmemory")
  8. http.New(c).Listen()
  9. }

server.go

package http

import (
    "encoding/json"
    "io/ioutil"
    "log"
    "mycache/cache"
    "net/http"
    "strings"
)

type Server struct {
    cache.Cache
}

func New(c cache.Cache) *Server {
    return &Server{c}
}

func (s *Server) Listen() {
    http.Handle("/cache/", s.cacheHandler())
    http.Handle("/status", s.statusHandler())
    http.ListenAndServe(":12345", nil)
}

func (s *Server) cacheHandler() http.Handler {
    return &cacheHandler{s}
}

type cacheHandler struct {
    *Server
}

func (h *cacheHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    key := strings.Split(r.URL.EscapedPath(), "/")[2]
    if len(key) == 0 {
        w.WriteHeader(http.StatusBadRequest)
        return
    }
    m := r.Method
    switch m {
    case http.MethodPut:
        // 添加
        b, err := ioutil.ReadAll(r.Body)
        if err != nil {
            w.WriteHeader(http.StatusInternalServerError)
            return
        }
        if len(b) != 0 {
            err = h.Set(key, b)
            if err != nil {
                w.WriteHeader(http.StatusInternalServerError)
                return
            }
        }
    case http.MethodGet:
        b, err := h.Get(key)
        if err != nil {
            w.WriteHeader(http.StatusInternalServerError)
            return
        }
        if len(b) == 0 {
            w.WriteHeader(http.StatusNotFound)
            return
        }
        w.Write(b)
        return
    case http.MethodDelete:
        err := h.Del(key)
        if err != nil {
            w.WriteHeader(http.StatusInternalServerError)
            return
        }
    default:
        w.WriteHeader(http.StatusMethodNotAllowed)
    }
}

func (s *Server) statusHandler() http.Handler {
    return &statusHandler{s}
}

type statusHandler struct {
    *Server
}

func (h *statusHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodGet {
        w.WriteHeader(http.StatusMethodNotAllowed)
        return
    }
    b, e := json.Marshal(h.GetStatus())
    if e != nil {
        log.Println(e)
        w.WriteHeader(http.StatusInternalServerError)
        return
    }
    w.Write(b)
}

cache.go

package cache

import (
    "log"
    "sync"
)

type Cache interface {
    Set(string, []byte) error
    Get(string) ([]byte, error)
    Del(string) error
    GetStatus() Status
}

type inMemoryCache struct {
    c     map[string][]byte
    mutex sync.RWMutex
    Status
}

func (i *inMemoryCache) Set(k string, v []byte) error {
    i.mutex.Lock()
    defer i.mutex.Unlock()
    i.c[k] = v
    i.add(k, v)
    return nil
}

func (i *inMemoryCache) Get(k string) ([]byte, error) {
    i.mutex.Lock()
    defer i.mutex.Unlock()
    return i.c[k], nil
}

func (i *inMemoryCache) Del(k string) error {
    i.mutex.Lock()
    defer i.mutex.Unlock()
    v, exist := i.c[k]
    if exist {
        delete(i.c, k)
        i.del(k, v)
    }
    return nil
}

func (i *inMemoryCache) GetStatus() Status {
    return i.Status
}

type Status struct {
    Count     int64
    KeySize   int64
    ValueSize int64
}

func (s *Status) add(k string, v []byte) {
    s.Count += 1
    s.KeySize += int64(len(k))
    s.ValueSize += int64(len(v))
}

func (s *Status) del(k string, v []byte) {
    s.Count -= 1
    s.KeySize -= int64(len(k))
    s.ValueSize -= int64(len(v))
}

func New(typ string) Cache {
    var c Cache
    if typ == "inmemory" {
        c = newInMemoryCache()
    }
    if c == nil {
        panic("unknow cache type " + typ)
    }
    log.Println(typ, "ready to serve")
    return c
}

func newInMemoryCache() Cache {
    c := &inMemoryCache{}
    c.c = make(map[string][]byte)
    c.mutex = sync.RWMutex{}
    c.Status = Status{}
    return c
}