My goal is to understand Effective Go about channel.
The problem is sender and receives block until both the sender and receiver are ready, forcing me to use go func() {}(). Honestly, I am not sure the use of chan.
code with go func() {}
type Ping chan string
func main() {
messages := make(Ping)
go func() { messages <- "ping" }()
msg := <-messages
fmt.Println(msg)
ch := make(Chan)
http.Handle("/test", ch)
go func() {
for {
fmt.Println(<-ch)
}
}()
http.ListenAndServe(":80", nil)
}
// A channel that sends a notification on each visit.
// (Probably want the channel to be buffered.)
type Chan chan *http.Request
func (ch Chan) ServeHTTP(w http.ResponseWriter, req *http.Request) {
ch <- req
fmt.Fprint(w, "notification sent")
}
or is chan supposedly to be used long with go statement? and in real world use, e.g API notification, function inside that go statement should live forever with for {} statement.
func worker(done chan *http.Request) {
for {
fmt.Println(<-done)
}
}
func main() {
messages := make(Ping)
go func() { messages <- "ping" }()
msg := <-messages
fmt.Println(msg)
ch := make(Chan)
http.Handle("/test", ch)
go worker(ch)
http.ListenAndServe(":80", nil)
}