Skip to content

Instantly share code, notes, and snippets.

@asmedrano
Last active August 29, 2015 13:57
Show Gist options
  • Save asmedrano/9456932 to your computer and use it in GitHub Desktop.
Save asmedrano/9456932 to your computer and use it in GitHub Desktop.
Fun with Go interfaces. In this case using io.Writer
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