main.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. // Grabs a folder and generates a go file with a map
  2. package main
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "log"
  7. "os"
  8. "path/filepath"
  9. )
  10. func main() {
  11. if len(os.Args) != 3 {
  12. fmt.Println("This will create a folder named by <pkgname> and add the generated file")
  13. fmt.Println("usage: ", os.Args[0], " <folder> <pkgname>")
  14. return
  15. }
  16. var folder = os.Args[1]
  17. var pkg = filepath.Base(os.Args[2]) // Remove trailing '/'
  18. var dst = os.Args[2]
  19. var data = map[string]string{}
  20. filepath.Walk(folder, func(fpath string, f os.FileInfo, err error) error {
  21. if f.IsDir() {
  22. return nil // Continue
  23. }
  24. // Get ABSPATH
  25. absFolder, err := filepath.Abs(folder)
  26. if err != nil {
  27. return err
  28. }
  29. absPath, err := filepath.Abs(fpath)
  30. if err != nil {
  31. return err
  32. }
  33. kfname := absPath[len(absFolder):]
  34. log.Printf("Processing: %s ", kfname)
  35. fdata, err := ioutil.ReadFile(fpath)
  36. if err != nil {
  37. log.Fatal(err)
  38. return err
  39. }
  40. vardata := ""
  41. for _, v := range fdata {
  42. vardata += fmt.Sprintf("\\x%02X", v)
  43. }
  44. data[kfname] = vardata
  45. return nil
  46. })
  47. // Write golang file
  48. os.Mkdir(dst, os.FileMode(0755))
  49. f, err := os.OpenFile(fmt.Sprintf("%s/%s.go", dst, pkg), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(0644))
  50. if err != nil {
  51. log.Fatal(err)
  52. }
  53. defer f.Close()
  54. f.WriteString("// Generated by folder2go\n")
  55. f.WriteString(fmt.Sprintf("package %s\n\n", pkg))
  56. // If we want http support
  57. // Templates would be nice here
  58. f.WriteString(`
  59. import (
  60. "mime"
  61. "net/http"
  62. "path/filepath"
  63. )
  64. `)
  65. f.WriteString("//Data exported data taken from folder\n")
  66. f.WriteString("var Data = map[string][]byte {\n")
  67. for k, v := range data {
  68. f.WriteString(fmt.Sprintf("\t\"%s\":\t\t[]byte(\"%s\"),\n", k, v))
  69. }
  70. f.WriteString("}\n")
  71. // Should be optional
  72. f.WriteString(`
  73. func AssetHandleFunc(w http.ResponseWriter, r *http.Request) {
  74. var solvedPath =r.URL.Path
  75. if solvedPath == "/" {
  76. solvedPath = "/index.html"
  77. }
  78. data, ok := Data[solvedPath]
  79. if !ok {
  80. w.WriteHeader(404)
  81. }
  82. w.Header().Set("Content-type",mime.TypeByExtension(filepath.Ext(solvedPath)))
  83. w.Write(data)
  84. }`)
  85. }