Golang map update on http handlefunc


I have a question about map in go language.
I want to handle the clients (http) and save some of their information using map (key (client IP) value pair) …
http handle each http client using a new thread, so I think changing (add, delete, edit) the map data will be unsafe … Is my action safe ?

package main

import (

func main() {
    var clientsData map[string]string
    http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
        // Is this map adding, safe or i have to use thread luck (mutex or ...) ?
        clientsData[request.RemoteAddr] = ...
    http.ListenAndServe("", nil)


If you only read, it is safe.

If you need to write, you need some way to do it “thread-safe”

The first idea is to use a sync.Mutex to protect the access to the map

However this may became a bottleneck, since you may have several requests in parallel but only one can write each time. We are talking about nanoseconds…

A second approach can be use a read/write mutex to control reading and writting. Many goroutines can read, but only one can write per time.

There are other options from package sync and sync/atomic.

There is one extra approach to consider: if you need only write into this map you can consider use a buffered channel to send a structure of key/value to be consumed in a single goroutine (responsible for store it into the map)

As you can see, this approach have many
Advantages IF it makes sense to your application.

You can even use channels to safe read / write via callbacks but this is another story.

If you have a doubt, write unit tests and use the race condition detector

Answered By – Tiago Peczenyj

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.