Fragment Description:



Select between http endpoints:
A http server, 2 http endpoints writeIt() and readIt(), based on a communication switch:
select.
Do some read:
curl http://localhost:8080/readIt Do some update:
curl http://localhost:8080/writeIt Then read again...

httpSelectWREndpoints

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

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

package main

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

type It string

var setIt = make(chan It)
var getIt = make(chan It)

func readOrWriteIt() {
    var t It
    log.Print("\n\nreadOrWriteIt listening on port:8080...\n")
    for {
        // a communication switch, each channel serializes the message transfered
        select {
        // either we receive an It from the setIt channel and write to t (update)
        case t = <-setIt:
            fmt.Printf("\n--->\tIt has been Written:\t%s", t)
        // or we send on the getIt channel the existing value of t
        case getIt <- t:
            fmt.Printf("\n--->\tIt has been Read:\t%s", t)
        }
    }
}
func writeIt(w http.ResponseWriter, r *http.Request) {
    // the channel setIt serializes the data sent on it
    setIt <- It(fmt.Sprintf("%v", time.Now()))
}
func readIt(w http.ResponseWriter, r *http.Request) {
    v := <-getIt
    fmt.Fprint(w, v)
}
func main() {
    go readOrWriteIt()

    // sending an It on the channel (the string is converted to an It).
    setIt <- It(fmt.Sprintf("\t%v", time.Now()))
    http.HandleFunc("/readIt", readIt)
    http.HandleFunc("/writeIt", writeIt)
    http.ListenAndServe(":8080", nil)
}



Comments