Skip to content

Instantly share code, notes, and snippets.

@bgnori
Created June 21, 2014 07:07
Show Gist options
  • Save bgnori/1aa5f4801e6b2e8b5bf8 to your computer and use it in GitHub Desktop.
Save bgnori/1aa5f4801e6b2e8b5bf8 to your computer and use it in GitHub Desktop.
アクセスカウンタをgo routineとchanで作ってみた.
package main
import (
"net/http"
"html/template"
)
type Page struct {
Title string
Count int
}
func bind(add chan int, result chan int) http.HandlerFunc {
//w http.ResponseWriter, r *http.ResponseWriter) {
return func (w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("count.html")
add <- 1
p := &Page{Title: "count", Count: <- result}
t.Execute(w, p)
}
}
func main() {
add := make(chan int)
result := make(chan int)
go func () {
acc := 0
for {
select {
case x := <-add:
acc += x
result <- acc
}
}
}()
http.HandleFunc("/", bind(add, result))
http.ListenAndServe(":8080", nil)
}
<h1>{{.Title |html}}</h1>
<div> count = {{.Count}} </div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment