Common isomorphic functionality in one kit.

static.go 2.2KB

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