7f09f943b133794408beeb1f216543600f125376
[project/luci.git] / libs / http / luasrc / http / protocol / mime.lua
1 --[[
2
3 HTTP protocol implementation for LuCI - mime handling
4 (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
5
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
9
10         http://www.apache.org/licenses/LICENSE-2.0
11
12 $Id$
13
14 ]]--
15
16 module("luci.http.protocol.mime", package.seeall)
17
18 require("luci.util")
19
20
21 -- MIME mapping
22 MIME_TYPES = {
23     ["txt"]   = "text/plain";
24     ["js"]    = "text/javascript";
25     ["css"]   = "text/css";
26     ["htm"]   = "text/html";
27     ["html"]  = "text/html";
28
29     ["gif"]   = "image/gif";
30     ["png"]   = "image/png";
31     ["jpg"]   = "image/jpeg";
32     ["jpeg"]  = "image/jpeg";
33
34     ["xml"]   = "application/xml";
35 }
36
37 -- extract extension from a filename and return corresponding mime-type or
38 -- "application/octet-stream" if the extension is unknown
39 function to_mime(filename)
40         if type(filename) == "string" then
41                 local ext = filename:match("[^%.]+$")
42
43                 if ext and MIME_TYPES[ext:lower()] then
44                         return MIME_TYPES[ext:lower()]
45                 end
46         end
47
48         return "application/octet-stream"
49 end
50
51 -- return corresponding extension for a given mime type or nil if the
52 -- given mime-type is unknown
53 function to_ext(mimetype)
54         if type(mimetype) == "string" then
55                 for ext, type in luci.util.kspairs( MIME_TYPES ) do
56                         if type == mimetype then
57                                 return ext
58                         end
59                 end
60         end
61
62         return nil
63 end