uri.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. // Replace with strings.Cut() when Go 1.18 is our new base version.
  43. semicolonIndex := strings.IndexByte(mimeTypeFull, ';')
  44. if semicolonIndex == -1 {
  45. return mimeTypeFull
  46. }
  47. return mimeTypeFull[:semicolonIndex]
  48. }
  49. func (u *uri) Scheme() string {
  50. return u.scheme
  51. }
  52. func (u *uri) String() string {
  53. // NOTE: this string reconstruction is mandated by IETF RFC3986,
  54. // section 5.3, pp. 35.
  55. s := u.scheme + "://" + u.authority + u.path
  56. if len(u.query) > 0 {
  57. s += "?" + u.query
  58. }
  59. if len(u.fragment) > 0 {
  60. s += "#" + u.fragment
  61. }
  62. return s
  63. }
  64. func (u *uri) Authority() string {
  65. return u.authority
  66. }
  67. func (u *uri) Path() string {
  68. return u.path
  69. }
  70. func (u *uri) Query() string {
  71. return u.query
  72. }
  73. func (u *uri) Fragment() string {
  74. return u.fragment
  75. }