Common isomorphic functionality in one kit.

static.go 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package isokit
  2. import (
  3. "io/ioutil"
  4. "log"
  5. "os"
  6. "path/filepath"
  7. "regexp"
  8. )
  9. var StaticAssetsPath string
  10. var CogStaticAssetsSearchPaths []string
  11. func RegisterStaticAssetsSearchPath(path string) {
  12. //fmt.Println("cog search path: ", path)
  13. CogStaticAssetsSearchPaths = append(CogStaticAssetsSearchPaths, path)
  14. }
  15. func findStaticAssets(ext string, paths []string) []string {
  16. var files []string
  17. for i := 0; i < len(paths); i++ {
  18. //fmt.Println("file search path: ", paths[i])
  19. filepath.Walk(paths[i], func(path string, f os.FileInfo, _ error) error {
  20. if !f.IsDir() {
  21. r, err := regexp.MatchString(ext, f.Name())
  22. if err == nil && r {
  23. files = append(files, path)
  24. }
  25. }
  26. return nil
  27. })
  28. }
  29. return files
  30. }
  31. func bundleJavaScript(jsfiles []string) {
  32. var result []byte = make([]byte, 0)
  33. if StaticAssetsPath == "" {
  34. return
  35. }
  36. if _, err := os.Stat(StaticAssetsPath + "/js"); os.IsNotExist(err) {
  37. os.Mkdir(StaticAssetsPath+"/js", 0711)
  38. }
  39. destinationFile := StaticAssetsPath + "/js/cogimports.js"
  40. for i := 0; i < len(jsfiles); i++ {
  41. b, err := ioutil.ReadFile(jsfiles[i])
  42. if err != nil {
  43. log.Println(err)
  44. }
  45. result = append(result, b...)
  46. }
  47. err := ioutil.WriteFile(destinationFile, result, 0644)
  48. if err != nil {
  49. log.Println(err)
  50. }
  51. }
  52. func bundleCSS(cssfiles []string) {
  53. var result []byte = make([]byte, 0)
  54. if StaticAssetsPath == "" {
  55. return
  56. }
  57. if _, err := os.Stat(StaticAssetsPath + "/css"); os.IsNotExist(err) {
  58. os.Mkdir(StaticAssetsPath+"/css", 0711)
  59. }
  60. destinationFile := StaticAssetsPath + "/css/cogimports.css"
  61. for i := 0; i < len(cssfiles); i++ {
  62. b, err := ioutil.ReadFile(cssfiles[i])
  63. if err != nil {
  64. log.Println(err)
  65. }
  66. result = append(result, b...)
  67. }
  68. err := ioutil.WriteFile(destinationFile, result, 0644)
  69. if err != nil {
  70. log.Println(err)
  71. }
  72. }
  73. func BundleStaticAssets() {
  74. jsfiles := findStaticAssets(".js", CogStaticAssetsSearchPaths)
  75. bundleJavaScript(jsfiles)
  76. cssfiles := findStaticAssets(".css", CogStaticAssetsSearchPaths)
  77. bundleCSS(cssfiles)
  78. }
  79. func init() {
  80. CogStaticAssetsSearchPaths = make([]string, 0)
  81. }