local_cache.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2020 gorse Project Authors
  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 server
  15. import (
  16. "encoding/gob"
  17. std_errors "errors"
  18. "github.com/juju/errors"
  19. "os"
  20. "path/filepath"
  21. )
  22. // LocalCache is local cache for the server node.
  23. type LocalCache struct {
  24. path string
  25. ServerName string
  26. }
  27. // LoadLocalCache loads local cache from a file.
  28. func LoadLocalCache(path string) (*LocalCache, error) {
  29. state := &LocalCache{path: path}
  30. // check if file exists
  31. if _, err := os.Stat(path); err != nil {
  32. if std_errors.Is(err, os.ErrNotExist) {
  33. return state, errors.NotFoundf("local cache file %s", path)
  34. }
  35. return state, errors.Trace(err)
  36. }
  37. // open file
  38. f, err := os.Open(path)
  39. if err != nil {
  40. return state, errors.Trace(err)
  41. }
  42. defer f.Close()
  43. decoder := gob.NewDecoder(f)
  44. if err = decoder.Decode(&state.ServerName); err != nil {
  45. return nil, errors.Trace(err)
  46. }
  47. return state, nil
  48. }
  49. // WriteLocalCache writes local cache to a file.
  50. func (s *LocalCache) WriteLocalCache() error {
  51. // create parent folder if not exists
  52. parent := filepath.Dir(s.path)
  53. if _, err := os.Stat(parent); os.IsNotExist(err) {
  54. err = os.MkdirAll(parent, os.ModePerm)
  55. if err != nil {
  56. return errors.Trace(err)
  57. }
  58. }
  59. // create file
  60. f, err := os.Create(s.path)
  61. if err != nil {
  62. return errors.Trace(err)
  63. }
  64. defer f.Close()
  65. // write file
  66. encoder := gob.NewEncoder(f)
  67. return errors.Trace(encoder.Encode(s.ServerName))
  68. }