123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- // Grabs a folder and generates a go file with a map
- package main
- import (
- "fmt"
- "io/ioutil"
- "log"
- "os"
- "path/filepath"
- )
- func main() {
- if len(os.Args) != 3 {
- fmt.Println("This will create a folder named by <pkgname> and add the generated file")
- fmt.Println("usage: ", os.Args[0], " <folder> <pkgname>")
- return
- }
- var folder = os.Args[1]
- var pkg = filepath.Base(os.Args[2]) // Remove trailing '/'
- var dst = os.Args[2]
- var data = map[string]string{}
- filepath.Walk(folder, func(fpath string, f os.FileInfo, err error) error {
- if f.IsDir() {
- return nil // Continue
- }
- // Get ABSPATH
- absFolder, err := filepath.Abs(folder)
- if err != nil {
- return err
- }
- absPath, err := filepath.Abs(fpath)
- if err != nil {
- return err
- }
- kfname := absPath[len(absFolder):]
- log.Printf("Processing: %s ", kfname)
- fdata, err := ioutil.ReadFile(fpath)
- if err != nil {
- log.Fatal(err)
- return err
- }
- vardata := ""
- for _, v := range fdata {
- vardata += fmt.Sprintf("\\x%02X", v)
- }
- data[kfname] = vardata
- return nil
- })
- // Write golang file
- os.Mkdir(dst, os.FileMode(0755))
- f, err := os.OpenFile(fmt.Sprintf("%s/%s.go", dst, pkg), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(0644))
- if err != nil {
- log.Fatal(err)
- }
- defer f.Close()
- f.WriteString("// Generated by folder2go\n")
- f.WriteString(fmt.Sprintf("package %s\n\n", pkg))
- // If we want http support
- // Templates would be nice here
- f.WriteString(`
- import (
- "mime"
- "net/http"
- "path/filepath"
- )
- `)
- f.WriteString("//Data exported data taken from folder\n")
- f.WriteString("var Data = map[string][]byte {\n")
- for k, v := range data {
- f.WriteString(fmt.Sprintf("\t\"%s\":\t\t[]byte(\"%s\"),\n", k, v))
- }
- f.WriteString("}\n")
- // Should be optional
- f.WriteString(`
- func AssetHandleFunc(w http.ResponseWriter, r *http.Request) {
- var solvedPath =r.URL.Path
- if solvedPath == "/" {
- solvedPath = "/index.html"
- }
- data, ok := Data[solvedPath]
- if !ok {
- w.WriteHeader(404)
- }
- w.Header().Set("Content-type",mime.TypeByExtension(filepath.Ext(solvedPath)))
- w.Write(data)
- }`)
- }
|