uri.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package repository
  2. import (
  3. "bufio"
  4. "mime"
  5. "path/filepath"
  6. "strings"
  7. "unicode/utf8"
  8. "fyne.io/fyne/v2"
  9. )
  10. // Declare conformance with fyne.URI interface.
  11. var _ fyne.URI = &uri{}
  12. type uri struct {
  13. scheme string
  14. authority string
  15. path string
  16. query string
  17. fragment string
  18. }
  19. func (u *uri) Extension() string {
  20. return filepath.Ext(u.path)
  21. }
  22. func (u *uri) Name() string {
  23. return filepath.Base(u.path)
  24. }
  25. func (u *uri) MimeType() string {
  26. mimeTypeFull := mime.TypeByExtension(u.Extension())
  27. if mimeTypeFull == "" {
  28. mimeTypeFull = "text/plain"
  29. repo, err := ForURI(u)
  30. if err != nil {
  31. return "application/octet-stream"
  32. }
  33. readCloser, err := repo.Reader(u)
  34. if err == nil {
  35. defer readCloser.Close()
  36. scanner := bufio.NewScanner(readCloser)
  37. if scanner.Scan() && !utf8.Valid(scanner.Bytes()) {
  38. mimeTypeFull = "application/octet-stream"
  39. }
  40. }
  41. }
  42. return strings.Split(mimeTypeFull, ";")[0]
  43. }
  44. func (u *uri) Scheme() string {
  45. return u.scheme
  46. }
  47. func (u *uri) String() string {
  48. // NOTE: this string reconstruction is mandated by IETF RFC3986,
  49. // section 5.3, pp. 35.
  50. s := u.scheme + "://" + u.authority + u.path
  51. if len(u.query) > 0 {
  52. s += "?" + u.query
  53. }
  54. if len(u.fragment) > 0 {
  55. s += "#" + u.fragment
  56. }
  57. return s
  58. }
  59. func (u *uri) Authority() string {
  60. return u.authority
  61. }
  62. func (u *uri) Path() string {
  63. return u.path
  64. }
  65. func (u *uri) Query() string {
  66. return u.query
  67. }
  68. func (u *uri) Fragment() string {
  69. return u.fragment
  70. }