resource.go 2.1 KB

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