forked from Code-Sharp/uHttpSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIHttpContext.cs
More file actions
83 lines (59 loc) · 2.29 KB
/
IHttpContext.cs
File metadata and controls
83 lines (59 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Text;
using uhttpsharp.Headers;
namespace uhttpsharp {
public interface IHttpContext {
IHttpRequest Request { get; }
IHttpResponse Response { get; set; }
ICookiesStorage Cookies { get; }
dynamic State { get; }
EndPoint RemoteEndPoint { get; }
}
public interface ICookiesStorage : IHttpHeaders {
bool Touched { get; }
void Upsert(string key, string value);
void Remove(string key);
string ToCookieData();
}
public class CookiesStorage : ICookiesStorage {
private static readonly string[] CookieSeparators = {"; ", "="};
private readonly Dictionary<string, string> _values;
public CookiesStorage(string cookie) {
var keyValues = cookie.Split(CookieSeparators, StringSplitOptions.RemoveEmptyEntries);
_values = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
for (var i = 0; i < keyValues.Length; i += 2) {
var key = keyValues[i];
var value = keyValues[i + 1];
_values[key] = value;
}
}
public bool Touched { get; private set; }
public string ToCookieData() {
var builder = new StringBuilder();
foreach (var kvp in _values) builder.AppendFormat("Set-Cookie: {0}={1}{2}", kvp.Key, kvp.Value, Environment.NewLine);
return builder.ToString();
}
public void Upsert(string key, string value) {
_values[key] = value;
Touched = true;
}
public void Remove(string key) {
if (_values.Remove(key)) Touched = true;
}
public IEnumerator<KeyValuePair<string, string>> GetEnumerator() {
return _values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
public string GetByName(string name) {
return _values[name];
}
public bool TryGetByName(string name, out string value) {
return _values.TryGetValue(name, out value);
}
}
}