Skip to content

Instantly share code, notes, and snippets.

@mtilson
Last active January 14, 2020 22:58
Show Gist options
  • Save mtilson/b2107e0b86c59daf6ea3c12cd1726100 to your computer and use it in GitHub Desktop.
Save mtilson/b2107e0b86c59daf6ea3c12cd1726100 to your computer and use it in GitHub Desktop.
how to count http request with goroutine and channel - in 20 code lines [golang] [20lines]
package main
import "fmt"
import "net/http"
var counterChan chan int
func counter() {
for i := 0; ; i++ { counterChan <- i }
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%d\n", <-counterChan)
}
func main() {
counterChan = make(chan int)
go counter()
http.HandleFunc("/", handler)
http.ListenAndServe(":8765", nil)
}
$ curl -s http://localhost:8765
0
$ curl -s http://localhost:8765
1
$ curl -s http://localhost:8765
2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment