1
0

assets.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2016 fatedier, fatedier@gmail.com
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package assets
  15. //go:generate statik -src=./static
  16. //go:generate go fmt statik/statik.go
  17. import (
  18. "io/ioutil"
  19. "net/http"
  20. "os"
  21. "path"
  22. "github.com/rakyll/statik/fs"
  23. _ "github.com/fatedier/frp/assets/statik"
  24. )
  25. var (
  26. // store static files in memory by statik
  27. FileSystem http.FileSystem
  28. // if prefix is not empty, we get file content from disk
  29. prefixPath string
  30. )
  31. // if path is empty, load assets in memory
  32. // or set FileSystem using disk files
  33. func Load(path string) (err error) {
  34. prefixPath = path
  35. if prefixPath != "" {
  36. FileSystem = http.Dir(prefixPath)
  37. return nil
  38. } else {
  39. FileSystem, err = fs.New()
  40. }
  41. return err
  42. }
  43. func ReadFile(file string) (content string, err error) {
  44. if prefixPath == "" {
  45. file, err := FileSystem.Open(path.Join("/", file))
  46. if err != nil {
  47. return content, err
  48. }
  49. buf, err := ioutil.ReadAll(file)
  50. if err != nil {
  51. return content, err
  52. }
  53. content = string(buf)
  54. } else {
  55. file, err := os.Open(path.Join(prefixPath, file))
  56. if err != nil {
  57. return content, err
  58. }
  59. buf, err := ioutil.ReadAll(file)
  60. if err != nil {
  61. return content, err
  62. }
  63. content = string(buf)
  64. }
  65. return content, err
  66. }