assets.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. defer file.Close()
  51. buf, err := ioutil.ReadAll(file)
  52. if err != nil {
  53. return content, err
  54. }
  55. content = string(buf)
  56. } else {
  57. file, err := os.Open(path.Join(prefixPath, file))
  58. if err != nil {
  59. return content, err
  60. }
  61. defer file.Close()
  62. buf, err := ioutil.ReadAll(file)
  63. if err != nil {
  64. return content, err
  65. }
  66. content = string(buf)
  67. }
  68. return content, err
  69. }