1
0
html2pic/main.go

44 lines
1.2 KiB
Go

package main
import (
"flag"
"io/ioutil"
"net/http"
"os"
"os/exec"
"yumc.pw/cloud/html2pic/uuid"
)
func main() {
b := flag.String("b", ":8080", "Server Bind Address")
lib := flag.String("lib", "/root", "Set Phantomjs Root Path")
tempDir := flag.String("temp", os.TempDir(), "")
flag.Parse()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
uid, _ := uuid.NewV4()
uuid := "html2pic-" + uid.String()
url, html := r.FormValue("url"), r.FormValue("html")
tempFile := *tempDir + "/" + uuid + ".html"
if html != "" {
ioutil.WriteFile(tempFile, []byte("<!DOCTYPE html><html lang=\"zh\"><head><meta charset=\"UTF-8\"></head><body style=\"margin: 0;padding: 0;\">"+html+"</body></html>"), os.ModeAppend)
url = "file://" + tempFile
defer os.Remove(tempFile)
}
if url == "" {
w.Write([]byte("Empty Url..."))
return
}
tempPic := *tempDir + "/" + uuid + ".png"
err := exec.Command(*lib+"/phantomjs", *lib+"/screenshot.js", url, tempPic).Run()
defer os.Remove(tempPic)
if err != nil {
w.Write([]byte(err.Error()))
return
}
bytes, _ := ioutil.ReadFile(tempPic)
w.Write(bytes)
})
http.ListenAndServe(*b, nil)
}