Created
July 4, 2016 06:15
-
-
Save sanmai/c0c4a129394a44a22a43eb362cf6e67b to your computer and use it in GitHub Desktop.
Simple counting server
This file contains hidden or 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" | |
"net/http" | |
) | |
func main() { | |
var count int | |
var countChan = make(chan bool) // unbuffered | |
var resultChan = make(chan chan int) | |
go func() { | |
for { | |
select { | |
case <-countChan: | |
count++ | |
case r := <-resultChan: | |
r <- count | |
} | |
} | |
}() | |
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
countChan <- true | |
}) | |
http.HandleFunc("/count", func(w http.ResponseWriter, r *http.Request) { | |
answerChan := make(chan int) | |
resultChan <- answerChan | |
fmt.Fprintf(w, "Count %d\n", <-answerChan) | |
}) | |
log.Fatal(http.ListenAndServe("localhost:8080", nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment