source: binary-improvements/7dtd-server-fixes/src/NetConnections/Servers/Web/StaticHandler.cs@ 173

Last change on this file since 173 was 154, checked in by alloc, 10 years ago

fixes

File size: 1.9 KB
RevLine 
[133]1using System;
2using System.Collections.Generic;
3using System.IO;
4using System.Net;
[134]5using System.Threading;
[133]6
7namespace AllocsFixes.NetConnections.Servers.Web
8{
9 public class StaticHandler : PathHandler
10 {
11 private string datapath;
12 private string staticPart;
13 private bool cache;
[134]14 private bool logMissingFiles;
[133]15 private Dictionary<string, byte[]> fileCache = new Dictionary<string, byte[]> ();
16
[134]17 public StaticHandler (string staticPart, string filePath, bool cache, bool logMissingFiles)
[133]18 {
19 this.staticPart = staticPart;
20 this.datapath = filePath;
21 this.cache = cache;
[134]22 this.logMissingFiles = logMissingFiles;
[133]23 }
24
[134]25 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, HttpListenerBasicIdentity user)
[133]26 {
27 try {
28 string fn = req.Url.AbsolutePath.Remove (0, staticPart.Length);
29
30 byte[] content;
31 if (cache) {
[134]32 Monitor.Enter (fileCache);
33 try {
34 if (!fileCache.ContainsKey (fn)) {
35 if (!File.Exists (datapath + "/" + fn)) {
[154]36 throw new FileNotFoundException ();
[134]37 }
38
39 fileCache.Add (fn, File.ReadAllBytes (datapath + "/" + fn));
[133]40 }
41
[134]42 content = fileCache [fn];
43 } finally {
44 Monitor.Exit (fileCache);
[133]45 }
46 } else {
47 if (!File.Exists (datapath + "/" + fn)) {
[154]48 throw new FileNotFoundException ();
[133]49 }
50
51 content = File.ReadAllBytes (datapath + "/" + fn);
52 }
53
54 resp.ContentType = MimeType.GetMimeType (Path.GetExtension (fn));
55 resp.ContentLength64 = content.Length;
56 resp.OutputStream.Write (content, 0, content.Length);
[154]57 } catch (FileNotFoundException e) {
58 resp.StatusCode = (int)HttpStatusCode.NotFound;
59 if (logMissingFiles)
60 Log.Out ("Web:Static:FileNotFound: \"" + req.Url.AbsolutePath + "\" @ \"" + datapath + "/" + req.Url.AbsolutePath.Remove (0, staticPart.Length) + "\"");
61 return;
[133]62 } catch (Exception e) {
63 Log.Out ("Error in StaticHandler.HandleRequest: " + e);
64 }
65 }
66 }
67}
68
Note: See TracBrowser for help on using the repository browser.