rename backend to pkg

This commit is contained in:
Torkel Ödegaard
2014-08-12 20:45:41 +02:00
parent e7ce371ee8
commit 9e30599f1f
16 changed files with 10 additions and 10 deletions
+67
View File
@@ -0,0 +1,67 @@
package components
import (
"crypto/md5"
"encoding/hex"
"io"
"os"
"os/exec"
"path/filepath"
"time"
log "github.com/alecthomas/log4go"
)
type PhantomRenderer struct {
ImagesDir string
PhantomDir string
}
func (self *PhantomRenderer) RenderToPng(url string) (string, error) {
log.Info("PhantomRenderer::renderToPng url %v", url)
binPath, _ := filepath.Abs(filepath.Join(self.PhantomDir, "phantomjs"))
scriptPath, _ := filepath.Abs(filepath.Join(self.PhantomDir, "render.js"))
pngPath, _ := filepath.Abs(filepath.Join(self.ImagesDir, getHash(url)))
pngPath = pngPath + ".png"
cmd := exec.Command(binPath, scriptPath, "url="+url, "width=100", "height=100", "png="+pngPath)
stdout, err := cmd.StdoutPipe()
if err != nil {
return "", err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return "", err
}
err = cmd.Start()
if err != nil {
return "", err
}
go io.Copy(os.Stdout, stdout)
go io.Copy(os.Stdout, stderr)
done := make(chan error)
go func() {
cmd.Wait()
close(done)
}()
select {
case <-time.After(10 * time.Second):
if err := cmd.Process.Kill(); err != nil {
log.Error("failed to kill: %v", err)
}
case <-done:
}
return pngPath, nil
}
func getHash(text string) string {
hasher := md5.New()
hasher.Write([]byte(text))
return hex.EncodeToString(hasher.Sum(nil))
}
+35
View File
@@ -0,0 +1,35 @@
package components
import (
"io/ioutil"
"os"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestPhantomRender(t *testing.T) {
Convey("Can render url", t, func() {
tempDir, _ := ioutil.TempDir("", "img")
renderer := &PhantomRenderer{ImagesDir: tempDir, PhantomDir: "../../_vendor/phantomjs/"}
png, err := renderer.RenderToPng("http://www.google.com")
So(err, ShouldBeNil)
So(exists(png), ShouldEqual, true)
//_, err = os.Stat(store.getFilePathForDashboard("hello"))
//So(err, ShouldBeNil)
})
}
func exists(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
return false
}