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

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

Fixes

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