assets.go 1.8 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=./frps/static -dest=./frps
  16. //go:generate statik -src=./frpc/static -dest=./frpc
  17. //go:generate go fmt ./frps/statik/statik.go
  18. //go:generate go fmt ./frpc/statik/statik.go
  19. import (
  20. "io/ioutil"
  21. "net/http"
  22. "os"
  23. "path"
  24. "github.com/rakyll/statik/fs"
  25. )
  26. var (
  27. // store static files in memory by statik
  28. FileSystem http.FileSystem
  29. // if prefix is not empty, we get file content from disk
  30. prefixPath string
  31. )
  32. // if path is empty, load assets in memory
  33. // or set FileSystem using disk files
  34. func Load(path string) (err error) {
  35. prefixPath = path
  36. if prefixPath != "" {
  37. FileSystem = http.Dir(prefixPath)
  38. return nil
  39. } else {
  40. FileSystem, err = fs.New()
  41. }
  42. return err
  43. }
  44. func ReadFile(file string) (content string, err error) {
  45. if prefixPath == "" {
  46. file, err := FileSystem.Open(path.Join("/", file))
  47. if err != nil {
  48. return content, err
  49. }
  50. buf, err := ioutil.ReadAll(file)
  51. if err != nil {
  52. return content, err
  53. }
  54. content = string(buf)
  55. } else {
  56. file, err := os.Open(path.Join(prefixPath, file))
  57. if err != nil {
  58. return content, err
  59. }
  60. buf, err := ioutil.ReadAll(file)
  61. if err != nil {
  62. return content, err
  63. }
  64. content = string(buf)
  65. }
  66. return content, err
  67. }