Created
August 19, 2021 07:26
-
-
Save oofnivek/9a281ca2e35c9f1b2fa6dcef89457220 to your computer and use it in GitHub Desktop.
This file contains 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 ( | |
"fmt" | |
"log" | |
"sync" | |
"time" | |
"reflect" | |
"net/http" | |
"encoding/json" | |
"github.com/gorilla/mux" | |
) | |
func Root(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintf(w,"Gorilla!") | |
} | |
func Set(w http.ResponseWriter, r *http.Request) { | |
params := mux.Vars(r) | |
key := params["key"] | |
val := params["val"] | |
GetLock() | |
MAP[key] = val | |
MUTEX.Unlock() | |
log.Println("Set",key,val) | |
fmt.Fprintf(w,"OK") | |
} | |
func GetLock() { | |
for z:=0; z<RETRIES; z++ { | |
if IsMutexLocked(MUTEX) { | |
time.Sleep(2 * time.Second) | |
} else { | |
break | |
} | |
} | |
MUTEX.Lock() | |
} | |
func Get(w http.ResponseWriter, r *http.Request) { | |
params := mux.Vars(r) | |
key := params["key"] | |
GetLock() | |
val := "" | |
if _, ok := MAP[key]; ok { | |
val = MAP[key] | |
} | |
MUTEX.Unlock() | |
log.Println("Get",key,val) | |
fmt.Fprintf(w,val) | |
} | |
func Del(w http.ResponseWriter, r *http.Request) { | |
params := mux.Vars(r) | |
key := params["key"] | |
GetLock() | |
delete(MAP,key) | |
MUTEX.Unlock() | |
log.Println("Del",key) | |
fmt.Fprintf(w,"OK") | |
} | |
func List(w http.ResponseWriter, r *http.Request) { | |
GetLock() | |
obj, _ := json.MarshalIndent(MAP, "", " ") | |
MUTEX.Unlock() | |
log.Println("List",string(obj)) | |
fmt.Fprintf(w,string(obj)) | |
} | |
func Clear(w http.ResponseWriter, r *http.Request) { | |
GetLock() | |
MAP = make(map[string]string) | |
MUTEX.Unlock() | |
log.Println("Clear") | |
fmt.Fprintf(w,"OK") | |
} | |
func IsMutexLocked(m *sync.Mutex) bool { | |
state := reflect.ValueOf(m).Elem().FieldByName("state") | |
return state.Int()&MUTEX_LOCKED== MUTEX_LOCKED | |
} | |
const MUTEX_LOCKED = 1 | |
const RETRIES = 99 | |
var MAP = make(map[string]string) | |
var MUTEX = &sync.Mutex{} | |
func main() { | |
r := mux.NewRouter() | |
r.HandleFunc("/", Root) | |
r.HandleFunc("/set/{key:[a-zA-Z0-9]+}/{val}", Set) | |
r.HandleFunc("/get/{key:[a-zA-Z0-9]+}", Get) | |
r.HandleFunc("/del/{key:[a-zA-Z0-9]+}", Del) | |
r.HandleFunc("/list", List) | |
r.HandleFunc("/clear", Clear) | |
log.Fatal(http.ListenAndServe(":80", r)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment