resource.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package fyne
  2. import (
  3. "io"
  4. "net/http"
  5. "os"
  6. "path/filepath"
  7. )
  8. // Resource represents a single binary resource, such as an image or font.
  9. // A resource has an identifying name and byte array content.
  10. // The serialised path of a resource can be obtained which may result in a
  11. // blocking filesystem write operation.
  12. type Resource interface {
  13. Name() string
  14. Content() []byte
  15. }
  16. // StaticResource is a bundled resource compiled into the application.
  17. // These resources are normally generated by the fyne_bundle command included in
  18. // the Fyne toolkit.
  19. type StaticResource struct {
  20. StaticName string
  21. StaticContent []byte
  22. }
  23. // Name returns the unique name of this resource, usually matching the file it
  24. // was generated from.
  25. func (r *StaticResource) Name() string {
  26. return r.StaticName
  27. }
  28. // Content returns the bytes of the bundled resource, no compression is applied
  29. // but any compression on the resource is retained.
  30. func (r *StaticResource) Content() []byte {
  31. return r.StaticContent
  32. }
  33. // NewStaticResource returns a new static resource object with the specified
  34. // name and content. Creating a new static resource in memory results in
  35. // sharable binary data that may be serialised to the system cache location.
  36. func NewStaticResource(name string, content []byte) *StaticResource {
  37. return &StaticResource{
  38. StaticName: name,
  39. StaticContent: content,
  40. }
  41. }
  42. // LoadResourceFromPath creates a new StaticResource in memory using the contents of the specified file.
  43. func LoadResourceFromPath(path string) (Resource, error) {
  44. bytes, err := os.ReadFile(filepath.Clean(path))
  45. if err != nil {
  46. return nil, err
  47. }
  48. name := filepath.Base(path)
  49. return NewStaticResource(name, bytes), nil
  50. }
  51. // LoadResourceFromURLString creates a new StaticResource in memory using the body of the specified URL.
  52. func LoadResourceFromURLString(urlStr string) (Resource, error) {
  53. res, err := http.Get(urlStr)
  54. if err != nil {
  55. return nil, err
  56. }
  57. defer res.Body.Close()
  58. bytes, err := io.ReadAll(res.Body)
  59. if err != nil {
  60. return nil, err
  61. }
  62. name := filepath.Base(urlStr)
  63. return NewStaticResource(name, bytes), nil
  64. }