Debian Codegraph @

http.go

raw
1 // ⚡️ Fiber is an Express inspired web framework written in Go with ☕️
2 // 🤖 Github Repository: https://github.com/gofiber/fiber
3 // 📌 API Documentation: https://docs.gofiber.io
4
5 package utils
6
7 import (
8 "mime"
9 "strings"
10
11 casestrings "github.com/gofiber/utils/v2/strings"
12 "github.com/gofiber/utils/v2/swar"
13 )
14
15 const MIMEOctetStream = "application/octet-stream"
16 const (
17 contentTypeApplicationJSON = "application/json"
18 contentTypeApplicationXML = "application/xml"
19 contentTypeApplicationFormURLEncoded = "application/x-www-form-urlencoded"
20 contentTypePrefixApplicationWithSlash = "application/"
21 )
22
23 // Extensions are looked up in an open-addressed table keyed by the extension
24 // packed into one lower-cased word and built from mimeExtensions at init: a
25 // hit is a multiply, a shift, and usually one comparison, with no allocation.
26 const (
27 mimeTableBits = 9 // 512 slots for ~130 entries
28 mimeTableMask = 1<<mimeTableBits - 1
29 mimeTableMaxEntries = 1 << (mimeTableBits - 1) // half full at most, so probes stay short and always end at a free slot
30 mimeHashMul = 0x9E3779B97F4A7C15 // Fibonacci hashing multiplier
31 mimeKeyMaxLen = swar.WordLen - 1 // the top lane of a key holds the length
32 )
33
34 type mimeEntry struct {
35 key uint64
36 mimeType string
37 }
38
39 var mimeTable = buildMIMETable(mimeExtensions)
40
41 func buildMIMETable(exts map[string]string) [1 << mimeTableBits]mimeEntry {
42 if len(exts) > mimeTableMaxEntries {
43 panic("utils: the MIME extension table holds at most " + FormatInt(mimeTableMaxEntries) + " entries; raise mimeTableBits")
44 }
45 var t [1 << mimeTableBits]mimeEntry
46 for ext, mimeType := range exts {
47 if ext == "" || len(ext) > mimeKeyMaxLen {
48 panic("utils: MIME extension \"" + ext + "\" must be 1.." + FormatInt(mimeKeyMaxLen) + " bytes to fit a packed key")
49 }
50 key := packExtension(ext)
51 h := mimeHash(key)
52 for t[h].mimeType != "" {
53 h = (h + 1) & mimeTableMask
54 }
55 t[h] = mimeEntry{key: key, mimeType: mimeType}
56 }
57 return t
58 }
59
60 // packExtension packs 1..mimeKeyMaxLen bytes lower-cased into a little-endian
61 // word with the length in the top lane, so "html\x00" and "html" differ.
62 func packExtension(ext string) uint64 {
63 return foldNeedle(ext) | uint64(len(ext))<<(8*mimeKeyMaxLen)
64 }
65
66 func mimeHash(key uint64) int {
67 return int(key * mimeHashMul >> (64 - mimeTableBits))
68 }
69
70 // GetMIME returns the content-type of a file extension, matched
71 // case-insensitively with or without the leading dot. Unknown extensions map
72 // to MIMEOctetStream; an empty extension yields an empty string.
73 func GetMIME(extension string) string {
74 if len(extension) == 0 {
75 return ""
76 }
77
78 ext := extension
79 if ext[0] == '.' {
80 ext = ext[1:]
81 }
82 if len(ext) > 0 && len(ext) <= mimeKeyMaxLen {
83 key := packExtension(ext)
84 for h := mimeHash(key); mimeTable[h].mimeType != ""; h = (h + 1) & mimeTableMask {
85 if mimeTable[h].key == key {
86 return mimeTable[h].mimeType
87 }
88 }
89 }
90
91 // Fallback to the mime package, which wants the dotted form.
92 if extension[0] != '.' {
93 extension = "." + extension
94 }
95 if foundMime := mime.TypeByExtension(extension); foundMime != "" {
96 return foundMime
97 }
98
99 return MIMEOctetStream
100 }
101
102 // ParseVendorSpecificContentType check if content type is vendor specific and
103 // if it is parsable to any known types. If its not vendor specific then returns
104 // the original content type.
105 func ParseVendorSpecificContentType(cType string, caseInsensitive ...bool) string {
106 useLower := len(caseInsensitive) > 0 && caseInsensitive[0]
107
108 working := cType
109 if useLower {
110 // Content types are case-insensitive. Normalize if requested using the
111 // strings.ToLower function to avoid allocations when possible.
112 working = casestrings.ToLower(cType)
113 }
114 plusIndex := strings.IndexByte(working, '+')
115
116 if plusIndex == -1 {
117 return cType
118 }
119
120 var parsableType string
121 if semiColonIndex := strings.IndexByte(working, ';'); semiColonIndex == -1 {
122 parsableType = working[plusIndex+1:]
123 } else if plusIndex < semiColonIndex {
124 parsableType = working[plusIndex+1 : semiColonIndex]
125 } else {
126 return cType[:semiColonIndex]
127 }
128
129 slashIndex := strings.IndexByte(working, '/')
130
131 if slashIndex == -1 {
132 return cType
133 }
134
135 if strings.HasPrefix(working, contentTypePrefixApplicationWithSlash) {
136 switch parsableType {
137 case "json":
138 return contentTypeApplicationJSON
139 case "xml":
140 return contentTypeApplicationXML
141 case "x-www-form-urlencoded":
142 return contentTypeApplicationFormURLEncoded
143 }
144 }
145
146 return working[:slashIndex+1] + parsableType
147 }
148
149 // limits for HTTP statuscodes
150 const (
151 statusMessageMin = 100
152 statusMessageMax = 511
153 )
154
155 // StatusMessage returns the correct message for the provided HTTP statuscode
156 func StatusMessage(status int) string {
157 if status < statusMessageMin || status > statusMessageMax {
158 return ""
159 }
160 return statusMessage[status]
161 }
162
163 // NOTE: Keep this in sync with fiber's status code list
164 var statusMessage = []string{
165 100: "Continue", // StatusContinue
166 101: "Switching Protocols", // StatusSwitchingProtocols
167 102: "Processing", // StatusProcessing
168 103: "Early Hints", // StatusEarlyHints
169
170 200: "OK", // StatusOK
171 201: "Created", // StatusCreated
172 202: "Accepted", // StatusAccepted
173 203: "Non-Authoritative Information", // StatusNonAuthoritativeInformation
174 204: "No Content", // StatusNoContent
175 205: "Reset Content", // StatusResetContent
176 206: "Partial Content", // StatusPartialContent
177 207: "Multi-Status", // StatusMultiStatus
178 208: "Already Reported", // StatusAlreadyReported
179 226: "IM Used", // StatusIMUsed
180
181 300: "Multiple Choices", // StatusMultipleChoices
182 301: "Moved Permanently", // StatusMovedPermanently
183 302: "Found", // StatusFound
184 303: "See Other", // StatusSeeOther
185 304: "Not Modified", // StatusNotModified
186 305: "Use Proxy", // StatusUseProxy
187 306: "Switch Proxy", // StatusSwitchProxy
188 307: "Temporary Redirect", // StatusTemporaryRedirect
189 308: "Permanent Redirect", // StatusPermanentRedirect
190
191 400: "Bad Request", // StatusBadRequest
192 401: "Unauthorized", // StatusUnauthorized
193 402: "Payment Required", // StatusPaymentRequired
194 403: "Forbidden", // StatusForbidden
195 404: "Not Found", // StatusNotFound
196 405: "Method Not Allowed", // StatusMethodNotAllowed
197 406: "Not Acceptable", // StatusNotAcceptable
198 407: "Proxy Authentication Required", // StatusProxyAuthRequired
199 408: "Request Timeout", // StatusRequestTimeout
200 409: "Conflict", // StatusConflict
201 410: "Gone", // StatusGone
202 411: "Length Required", // StatusLengthRequired
203 412: "Precondition Failed", // StatusPreconditionFailed
204 413: "Request Entity Too Large", // StatusRequestEntityTooLarge
205 414: "Request URI Too Long", // StatusRequestURITooLong
206 415: "Unsupported Media Type", // StatusUnsupportedMediaType
207 416: "Requested Range Not Satisfiable", // StatusRequestedRangeNotSatisfiable
208 417: "Expectation Failed", // StatusExpectationFailed
209 418: "I'm a teapot", // StatusTeapot
210 421: "Misdirected Request", // StatusMisdirectedRequest
211 422: "Unprocessable Entity", // StatusUnprocessableEntity
212 423: "Locked", // StatusLocked
213 424: "Failed Dependency", // StatusFailedDependency
214 425: "Too Early", // StatusTooEarly
215 426: "Upgrade Required", // StatusUpgradeRequired
216 428: "Precondition Required", // StatusPreconditionRequired
217 429: "Too Many Requests", // StatusTooManyRequests
218 431: "Request Header Fields Too Large", // StatusRequestHeaderFieldsTooLarge
219 451: "Unavailable For Legal Reasons", // StatusUnavailableForLegalReasons
220
221 500: "Internal Server Error", // StatusInternalServerError
222 501: "Not Implemented", // StatusNotImplemented
223 502: "Bad Gateway", // StatusBadGateway
224 503: "Service Unavailable", // StatusServiceUnavailable
225 504: "Gateway Timeout", // StatusGatewayTimeout
226 505: "HTTP Version Not Supported", // StatusHTTPVersionNotSupported
227 506: "Variant Also Negotiates", // StatusVariantAlsoNegotiates
228 507: "Insufficient Storage", // StatusInsufficientStorage
229 508: "Loop Detected", // StatusLoopDetected
230 510: "Not Extended", // StatusNotExtended
231 511: "Network Authentication Required", // StatusNetworkAuthenticationRequired
232 }
233
234 // MIME types were copied from https://github.com/nginx/nginx/blob/67d2a9541826ecd5db97d604f23460210fd3e517/conf/mime.types with the following updates:
235 // - Use "application/xml" instead of "text/xml" as recommended per https://datatracker.ietf.org/doc/html/rfc7303#section-4.1
236 // - Use "text/javascript" instead of "application/javascript" as recommended per https://www.rfc-editor.org/rfc/rfc9239#name-text-javascript
237 // - Use "application/vnd.msgpack" from https://www.iana.org/assignments/media-types/application/vnd.msgpack
238 var mimeExtensions = map[string]string{
239 "html": "text/html",
240 "htm": "text/html",
241 "shtml": "text/html",
242 "css": "text/css",
243 "xml": "application/xml",
244 "cbor": "application/cbor",
245 "gif": "image/gif",
246 "jpeg": "image/jpeg",
247 "jpg": "image/jpeg",
248 "js": "text/javascript",
249 "atom": "application/atom+xml",
250 "rss": "application/rss+xml",
251 "mml": "text/mathml",
252 "txt": "text/plain",
253 "jad": "text/vnd.sun.j2me.app-descriptor",
254 "wml": "text/vnd.wap.wml",
255 "htc": "text/x-component",
256 "avif": "image/avif",
257 "png": "image/png",
258 "svg": "image/svg+xml",
259 "svgz": "image/svg+xml",
260 "tif": "image/tiff",
261 "tiff": "image/tiff",
262 "wbmp": "image/vnd.wap.wbmp",
263 "webp": "image/webp",
264 "ico": "image/x-icon",
265 "jng": "image/x-jng",
266 "bmp": "image/x-ms-bmp",
267 "woff": "font/woff",
268 "woff2": "font/woff2",
269 "jar": "application/java-archive",
270 "war": "application/java-archive",
271 "ear": "application/java-archive",
272 "json": "application/json",
273 "msgpack": "application/vnd.msgpack",
274 "hqx": "application/mac-binhex40",
275 "doc": "application/msword",
276 "pdf": "application/pdf",
277 "ps": "application/postscript",
278 "eps": "application/postscript",
279 "ai": "application/postscript",
280 "rtf": "application/rtf",
281 "m3u8": "application/vnd.apple.mpegurl",
282 "kml": "application/vnd.google-earth.kml+xml",
283 "kmz": "application/vnd.google-earth.kmz",
284 "xls": "application/vnd.ms-excel",
285 "eot": "application/vnd.ms-fontobject",
286 "ppt": "application/vnd.ms-powerpoint",
287 "odg": "application/vnd.oasis.opendocument.graphics",
288 "odp": "application/vnd.oasis.opendocument.presentation",
289 "ods": "application/vnd.oasis.opendocument.spreadsheet",
290 "odt": "application/vnd.oasis.opendocument.text",
291 "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
292 "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
293 "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
294 "wmlc": "application/vnd.wap.wmlc",
295 "wasm": "application/wasm",
296 "7z": "application/x-7z-compressed",
297 "cco": "application/x-cocoa",
298 "jardiff": "application/x-java-archive-diff",
299 "jnlp": "application/x-java-jnlp-file",
300 "run": "application/x-makeself",
301 "pl": "application/x-perl",
302 "pm": "application/x-perl",
303 "prc": "application/x-pilot",
304 "pdb": "application/x-pilot",
305 "rar": "application/x-rar-compressed",
306 "rpm": "application/x-redhat-package-manager",
307 "sea": "application/x-sea",
308 "swf": "application/x-shockwave-flash",
309 "sit": "application/x-stuffit",
310 "tcl": "application/x-tcl",
311 "tk": "application/x-tcl",
312 "der": "application/x-x509-ca-cert",
313 "pem": "application/x-x509-ca-cert",
314 "crt": "application/x-x509-ca-cert",
315 "xpi": "application/x-xpinstall",
316 "xhtml": "application/xhtml+xml",
317 "xspf": "application/xspf+xml",
318 "zip": "application/zip",
319 "zst": "application/zstd",
320 "bin": "application/octet-stream",
321 "exe": "application/octet-stream",
322 "dll": "application/octet-stream",
323 "deb": "application/octet-stream",
324 "dmg": "application/octet-stream",
325 "iso": "application/octet-stream",
326 "img": "application/octet-stream",
327 "msi": "application/octet-stream",
328 "msp": "application/octet-stream",
329 "msm": "application/octet-stream",
330 "mid": "audio/midi",
331 "midi": "audio/midi",
332 "kar": "audio/midi",
333 "mp3": "audio/mpeg",
334 "ogg": "audio/ogg",
335 "m4a": "audio/x-m4a",
336 "ra": "audio/x-realaudio",
337 "3gpp": "video/3gpp",
338 "3gp": "video/3gpp",
339 "ts": "video/mp2t",
340 "mp4": "video/mp4",
341 "mpeg": "video/mpeg",
342 "mpg": "video/mpeg",
343 "mov": "video/quicktime",
344 "webm": "video/webm",
345 "flv": "video/x-flv",
346 "m4v": "video/x-m4v",
347 "mng": "video/x-mng",
348 "asx": "video/x-ms-asf",
349 "asf": "video/x-ms-asf",
350 "wmv": "video/x-ms-wmv",
351 "avi": "video/x-msvideo",
352 }