1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.IO;
|
---|
4 | using System.Net;
|
---|
5 |
|
---|
6 | namespace 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 |
|
---|