cache.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package main
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "io"
  6. "os"
  7. "sync"
  8. "github.com/superp00t/etc"
  9. "github.com/superp00t/etc/yo"
  10. )
  11. var cacheLock = new(sync.Mutex)
  12. var cachePath etc.Path
  13. func initCache() {
  14. if !dirExists("cache") {
  15. mkdir("cache")
  16. }
  17. if !dirExists("cache") {
  18. yo.Fatal("could not create cache folder")
  19. }
  20. yo.Println("Initialized cache!")
  21. }
  22. func cacheLoad(host, path string) (io.Reader, bool, error) {
  23. h := etc.NewBuffer()
  24. h.WriteUString(host)
  25. h.WriteUString(path)
  26. chk := hex.EncodeToString(h.Sha512Digest())
  27. if !cachePath.Exists(chk[0:2]) {
  28. return nil, false, fmt.Errorf("no file found")
  29. }
  30. cpath := cachePath.GetSub(etc.Path{chk[0:2], chk}).Render()
  31. if !cachePath.Exists(cpath) {
  32. return nil, false, fmt.Errorf("no file found")
  33. }
  34. f, err := cachePath.Get(path)
  35. return f, false, err
  36. }
  37. func dirExists(path string) bool {
  38. i, err := os.Stat(path)
  39. if err == nil && i.IsDir() {
  40. return true
  41. }
  42. return false
  43. }
  44. func mkdir(path string) {
  45. err := os.MkdirAll(path, 0700)
  46. if err != nil {
  47. panic(err)
  48. }
  49. }