Created
November 3, 2018 23:35
-
-
Save sheki/d9a8ebee090fe76b485398f0f4e19c9d to your computer and use it in GitHub Desktop.
Solution for a recurse center problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"fmt" | |
"log" | |
"net/http" | |
"sync" | |
) | |
// Not fully production ready program | |
func main() { | |
s := &Server{store: newInMemStore()} | |
s.Start() | |
} | |
type inMemStore struct { | |
backingStore map[string]string | |
mutex *sync.RWMutex | |
} | |
func newInMemStore() *inMemStore { | |
return &inMemStore{backingStore: make(map[string]string), mutex: &sync.RWMutex{}} | |
} | |
func (i *inMemStore) get(k string) (string, error) { | |
i.mutex.RLock() | |
defer i.mutex.RUnlock() | |
res, ok := i.backingStore[k] | |
if !ok { | |
return "", errors.New("not found") | |
} | |
return res, nil | |
} | |
func (i *inMemStore) put(k, v string) error { | |
i.mutex.Lock() | |
defer i.mutex.Unlock() | |
i.backingStore[k] = v | |
return nil | |
} | |
type Store interface { | |
get(string) (string, error) | |
put(string, string) error | |
} | |
type Server struct { | |
store Store | |
} | |
func (s *Server) GetHandler(w http.ResponseWriter, r *http.Request) { | |
defer r.Body.Close() | |
err := r.ParseForm() | |
if err != nil { | |
http.Error(w, err.Error(), 500) | |
return | |
} | |
key := r.FormValue("key") | |
res, err := s.store.get(key) | |
if err != nil { | |
http.Error(w, err.Error(), 500) | |
return | |
} | |
fmt.Fprint(w, res) | |
} | |
func (s *Server) SetHandler(w http.ResponseWriter, r *http.Request) { | |
defer r.Body.Close() | |
err := r.ParseForm() | |
if err != nil { | |
http.Error(w, err.Error(), 500) | |
return | |
} | |
for k, v := range r.Form { | |
if len(v) != 1 { | |
continue | |
} | |
err := s.store.put(k, v[0]) | |
if err != nil { | |
http.Error(w, err.Error(), 500) | |
return | |
} | |
} | |
fmt.Fprint(w, "ok") | |
} | |
func (s *Server) Start() { | |
http.HandleFunc("/set", s.SetHandler) | |
http.HandleFunc("/get", s.GetHandler) | |
log.Fatal(http.ListenAndServe(":4000", nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment