Golang Concurrent Map

How to share a map or any other variable in a multi threaded environment in Go/Golang. For me, it happened very often in Gorilla Mux where I need temporary storage shared between requests but I do not want to store it in the database.

Code below is web clipboard.

package main

import (
"fmt"
"log"
"sync"
"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"]
MUTEX.Lock()
MAP[key] = val
MUTEX.Unlock()
log.Println("Set",key,val)
fmt.Fprintf(w,"OK")
}

func Get(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
key := params["key"]
MUTEX.Lock()
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"]
MUTEX.Lock()
delete(MAP,key)
MUTEX.Unlock()
log.Println("Del",key)
fmt.Fprintf(w,"OK")
}
func List(w http.ResponseWriter, r *http.Request) {
MUTEX.Lock()
obj, _ := json.MarshalIndent(MAP, "", " ")
MUTEX.Unlock()
log.Println("List",string(obj))
fmt.Fprintf(w,string(obj))
}

func Clear(w http.ResponseWriter, r *http.Request) {
MUTEX.Lock()
MAP = make(map[string]string)
MUTEX.Unlock()
log.Println("Clear",string(obj))
fmt.Fprintf(w,"OK")
}

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))
}

To set a variable with value. Use curl or your browser’s address bar. Limitation to this version is that the value you are trying to assign must not have “/” slash in it.

curl 'http://127.0.0.1/set/YOUR_VARIABLE/YOUR_VALUE'

To retrieve a variable’s value

curl 'http://127.0.0.1/get/YOUR_VARIABLE'

To list all variables

curl 'http://127.0.0.1/list'

To delete a variable

curl 'http://127.0.0.1/del/YOUR_VARIABLE'

To clear all variables

curl 'http://127.0.0.1/clear'

I modified my own version from the above vanilla version and now it does not have the “/” slash limitation. View it at https://clipboard.oofnivek.com

< Back to all the stories I had written

Written by

A software engineer, a rock climbing, diving & rollerblading enthusiast, a husband, a father.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store