Created
June 21, 2014 07:07
-
-
Save bgnori/1aa5f4801e6b2e8b5bf8 to your computer and use it in GitHub Desktop.
アクセスカウンタをgo routineとchanで作ってみた.
This file contains 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 ( | |
"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) | |
} |
This file contains 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
<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