Fragment Description:



For these endpoints, Writing and Reading are serialized with a Mutex.
A http server, 2 http endpoints:
writeIt() and readIt(), serialization thanks to a Mutex.
Do some read:
curl http://localhost:8080/readIt Do some update:
curl http://localhost:8080/writeIt

httpMutexRWEndpoint

Last update, on 2015, Tue 1 Dec, 15:31:34

/* ... <== see fragment description ... */

package main

import (
    "fmt"
    "log"
    "net/http"
    "sync"
    "time"
)

type It struct {
    // mu will serialize access to S, in Read and Write mode.
    // An RWMutex is a reader/writer mutual exclusion lock.
    // The lock can be held by an arbitrary number of readers or a single writer.
    mu sync.RWMutex
    S  string
}

var (
    it *It = &It{}
)

func writeIt(w http.ResponseWriter, r *http.Request) {
    // the Write accesses to the variable 'it.S' are serialized (not marshalled).
    it.mu.Lock()
    it.S = fmt.Sprintf("%v", time.Now())
    it.mu.Unlock()

    log.Printf("\n\tit.S has been written:\t%s...", it.S)
    fmt.Fprintf(w, "\n--->\tIt.s has been Written:\t%s\n----\n", it.S)
}
func readIt(w http.ResponseWriter, r *http.Request) {
    // the Read accesses to the variable 'it.S' are serialized too.
    it.mu.RLock()
    s := it.S
    it.mu.RUnlock()
    log.Printf("\n\tit.S has been read:\t\t%s...", it.S)

    fmt.Fprintf(w, "\n--->\tIt.s has been Read:\t%s\n====\n", s)
}
func main() {
    // write It a first time
    it.mu.Lock()
    it.S = fmt.Sprintf("%v", time.Now())
    it.mu.Unlock()

    http.HandleFunc("/readIt", readIt)
    http.HandleFunc("/writeIt", writeIt)

    log.Print("Server listening on port:8080...")
    http.ListenAndServe(":8080", nil)
}



Comments