Created
January 5, 2017 17:42
-
-
Save xcsrz/213964ee205eed5d560159662816954c to your computer and use it in GitHub Desktop.
Modeled after Golang's ioutil package's NopCloser method which wraps an io.Reader interface in an io.ReadCloser facade interface, this code takes an io.Writer and a nil channel and returns an io.WriteCloser interface. The example.go file demonstrates usage in an http.HandleFunc as a very over complicated counter using the worker-and-channel-over…
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 ( | |
"io" | |
"log" | |
"net/http" | |
"strconv" | |
) | |
func main() { | |
worker := NewWorker() | |
http.HandleFunc("/count", func(w http.ResponseWriter, r *http.Request) { | |
doneChan := make(chan struct{}) | |
worker.request <- WriteChanCloser(w, doneChan) | |
<-doneChan | |
}) | |
err := http.ListenAndServe(":8888", nil) | |
if err != nil { | |
log.Fatal("ListenAndServe: ", err) | |
} | |
} | |
type Worker struct { | |
count int | |
request chan io.WriteCloser | |
} | |
func (w *Worker) run() { | |
go func() { | |
for { | |
select { | |
case req := <-w.request: | |
w.count += 1 | |
req.Write([]byte(strconv.Itoa(w.count))) | |
req.Close() | |
} | |
} | |
}() | |
} | |
func NewWorker() *Worker { | |
w := &Worker{ | |
count: 0, | |
request: make(chan io.WriteCloser), | |
} | |
w.run() | |
return w | |
} |
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 "io" | |
type writeChanCloser struct { | |
io.Writer | |
closeChan chan struct{} | |
} | |
func (wcc writeChanCloser) Close() error { | |
close(wcc.closeChan) | |
return nil | |
} | |
// WriteChanCloser returns a WriteCloser with a Close method wrapping | |
// the provided Reader r. The Close method simply closes the provided | |
// nil channel. | |
func WriteChanCloser(r io.Writer, c chan struct{}) io.WriteCloser { | |
return writeChanCloser{r, c} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment