using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Threading; namespace AllocsFixes.NetConnections.Servers.Web { public class StaticHandler : PathHandler { private string datapath; private string staticPart; private bool cache; private bool logMissingFiles; private Dictionary fileCache = new Dictionary (); public StaticHandler (string staticPart, string filePath, bool cache, bool logMissingFiles) { this.staticPart = staticPart; this.datapath = filePath; this.cache = cache; this.logMissingFiles = logMissingFiles; } public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, HttpListenerBasicIdentity user) { try { string fn = req.Url.AbsolutePath.Remove (0, staticPart.Length); byte[] content; if (cache) { Monitor.Enter (fileCache); try { if (!fileCache.ContainsKey (fn)) { if (!File.Exists (datapath + "/" + fn)) { throw new FileNotFoundException (); } fileCache.Add (fn, File.ReadAllBytes (datapath + "/" + fn)); } content = fileCache [fn]; } finally { Monitor.Exit (fileCache); } } else { if (!File.Exists (datapath + "/" + fn)) { throw new FileNotFoundException (); } content = File.ReadAllBytes (datapath + "/" + fn); } resp.ContentType = MimeType.GetMimeType (Path.GetExtension (fn)); resp.ContentLength64 = content.Length; resp.OutputStream.Write (content, 0, content.Length); } catch (FileNotFoundException e) { resp.StatusCode = (int)HttpStatusCode.NotFound; if (logMissingFiles) Log.Out ("Web:Static:FileNotFound: \"" + req.Url.AbsolutePath + "\" @ \"" + datapath + "/" + req.Url.AbsolutePath.Remove (0, staticPart.Length) + "\""); return; } catch (Exception e) { Log.Out ("Error in StaticHandler.HandleRequest: " + e); } } } }