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

Last change on this file since 148 was 138, checked in by alloc, 10 years ago

Fixes

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