项目作者: hyperboloide

项目描述 :
A simple Go stream processing library that works like Unix pipes
高级语言: Go
项目地址: git://github.com/hyperboloide/pipe.git
创建时间: 2015-04-27T11:22:37Z
项目社区:https://github.com/hyperboloide/pipe

开源协议:MIT License

下载


pipe

Build Status
GoDoc
Go Report Card

A simple stream processing library that works like Unix pipes.
This library is fully asynchronous.
Create a Pipe from a Reader, add some transformation functions and get the result writed to a Writer.

To install :

  1. $ go get github.com/hyperboloide/pipe

Then add the following import :

  1. import "github.com/hyperboloide/pipe"

Example

Bellow is a very basic example that:

  1. Open a file
  2. Compress it
  3. Save it
  1. package main
  2. import (
  3. "compress/gzip"
  4. "github.com/hyperboloide/pipe"
  5. "io"
  6. "log"
  7. "os"
  8. )
  9. func zip(r io.Reader, w io.Writer) error {
  10. gzw, err := gzip.NewWriterLevel(w, gzip.BestSpeed)
  11. if err != nil {
  12. return err
  13. }
  14. defer gzw.Close()
  15. _, err = io.Copy(gzw, r)
  16. return err
  17. }
  18. func main() {
  19. // pipe input
  20. in, err := os.Open("test.txt")
  21. if err != nil {
  22. log.Fatal(err)
  23. }
  24. defer in.Close()
  25. // pipe output
  26. out, err := os.Create("test.txt.tgz")
  27. if err != nil {
  28. log.Fatal(err)
  29. }
  30. defer out.Close()
  31. // create a new pipe with a io.Reader
  32. // Push a transformation function
  33. // Set output
  34. // Exec and get errors if any
  35. if err := pipe.New(in).Push(zip).To(out).Exec(); err != nil {
  36. log.Fatal(err)
  37. }
  38. }

Readers and Writers

Pipe also provides a set of Reader/Writer to read from and write to.

Here is an example:

  1. import (
  2. "github.com/hyperboloide/pipe"
  3. "github.com/hyperboloide/pipe/rw"
  4. "log"
  5. "os"
  6. )
  7. func DemoRW() {
  8. in, err := os.Open("test.txt")
  9. if err != nil {
  10. log.Fatal(err)
  11. }
  12. defer in.Close()
  13. file := &rw.File{AllowSub: true}
  14. // Always start before use. Note that an RW after Start can be reused.
  15. if err := file.Start(); err != nil {
  16. log.Fatal(err)
  17. }
  18. // Obtain a writer
  19. w, err := file.NewWriter("copy.txt")
  20. if err != nil {
  21. log.Fatal(err)
  22. }
  23. // ToCloser() closes the connection at the end of the write.
  24. if err := pipe.New(binReader).ToCloser(w).Exec(); err != nil {
  25. log.Fatal(err)
  26. }
  27. }

It’s also easy to create your own, just implement the ReadWriteDeleter interface.