Last active
August 29, 2015 13:57
-
-
Save asmedrano/9456932 to your computer and use it in GitHub Desktop.
Fun with Go interfaces. In this case using io.Writer
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 ( | |
"fmt" | |
"io" | |
"os" | |
"time" | |
"path/filepath" | |
"github.com/garyburd/redigo/redis" | |
) | |
type RedisFile struct{ | |
connection redis.Conn // should this be a pointer? | |
name string | |
} | |
// establish a new redis connection and use name as the working key for the file | |
func (rf RedisFile) Open(name string) RedisWriter { | |
var err error | |
rf.connection, err = redis.DialTimeout("tcp", "127.0.0.1:6379" , 0, 1*time.Second, 1*time.Second) | |
if err != nil{ | |
panic(err) | |
} | |
rf.name = name | |
return RedisWriter {rf} | |
} | |
type RedisWriter struct{ | |
file RedisFile | |
} | |
func (rw RedisWriter) Write(p []byte) (n int, err error){ | |
_, rerr := rw.file.connection.Do("APPEND", rw.file.name, p) | |
if rerr != nil { | |
fmt.Println(rerr) | |
} | |
rw.file.connection.Do("PUBLISH", "cp_test_chan", rw.file.name) // publish the file into the file name channel | |
return len(p), nil | |
} | |
func main(){ | |
f := RedisFile{} | |
r, err := os.Open(os.Args[1]) | |
w := f.Open(filepath.Base(r.Name())) | |
if err != nil { | |
panic(err) | |
} | |
defer r.Close() | |
_, err = io.Copy(w, r) // Since our RedisWriter satisfies the Writer Interface we can just use io.Copy like it aint no thang. | |
if err != nil { | |
panic(err) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment