xs_mime.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /* copyright (c) 2022 - 2024 grunfink et al. / MIT license */
  2. #ifndef _XS_MIME_H
  3. #define _XS_MIME_H
  4. const char *xs_mime_by_ext(const char *file);
  5. extern const char *xs_mime_types[];
  6. #ifdef XS_IMPLEMENTATION
  7. /* intentionally brain-dead simple */
  8. /* CAUTION: sorted */
  9. const char *xs_mime_types[] = {
  10. "3gp", "video/3gpp",
  11. "aac", "audio/aac",
  12. "css", "text/css",
  13. "flac", "audio/flac",
  14. "flv", "video/flv",
  15. "gif", "image/gif",
  16. "gmi", "text/gemini",
  17. "html", "text/html",
  18. "jpeg", "image/jpeg",
  19. "jpg", "image/jpeg",
  20. "json", "application/json",
  21. "m4a", "audio/aac",
  22. "m4v", "video/mp4",
  23. "md", "text/markdown",
  24. "mov", "video/quicktime",
  25. "mp3", "audio/mp3",
  26. "mp4", "video/mp4",
  27. "mpg4", "video/mp4",
  28. "oga", "audio/ogg",
  29. "ogg", "audio/ogg",
  30. "ogv", "video/ogg",
  31. "opus", "audio/ogg",
  32. "png", "image/png",
  33. "svg", "image/svg+xml",
  34. "svgz", "image/svg+xml",
  35. "txt", "text/plain",
  36. "wav", "audio/wav",
  37. "webm", "video/webm",
  38. "webp", "image/webp",
  39. "wma", "audio/wma",
  40. "xml", "text/xml",
  41. NULL, NULL,
  42. };
  43. const char *xs_mime_by_ext(const char *file)
  44. /* returns the MIME type by file extension */
  45. {
  46. const char *ext = strrchr(file, '.');
  47. if (ext) {
  48. xs *uext = xs_tolower_i(xs_dup(ext + 1));
  49. int b = 0;
  50. int t = xs_countof(xs_mime_types) / 2 - 2;
  51. while (t >= b) {
  52. int n = (b + t) / 2;
  53. const char *p = xs_mime_types[n * 2];
  54. int c = strcmp(uext, p);
  55. if (c < 0)
  56. t = n - 1;
  57. else
  58. if (c > 0)
  59. b = n + 1;
  60. else
  61. return xs_mime_types[(n * 2) + 1];
  62. }
  63. }
  64. return "application/octet-stream";
  65. }
  66. #endif /* XS_IMPLEMENTATION */
  67. #endif /* XS_MIME_H */