-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEndpointHandler.cs
96 lines (81 loc) · 2.77 KB
/
EndpointHandler.cs
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
84
85
86
87
88
89
90
91
92
93
94
95
96
using System.Text.Json;
namespace DotnetRedfish;
public class EndpointHandler
{
private readonly string _rootPath;
private readonly ILogger<EndpointHandler> _logger;
public EndpointHandler(string? rootPath, ILogger<EndpointHandler> logger)
{
_logger = logger;
_rootPath = Directory.GetCurrentDirectory() + '/' + rootPath;
}
public async Task Handle(HttpContext context)
{
if (context.Request.Path.Value is null)
{
_logger.LogError("Get null request");
context.Response.StatusCode = 404;
return;
}
string relativePath = context.Request.Path.Value.Replace("/redfish/v1", string.Empty);
if (!relativePath.EndsWith('/'))
{
relativePath += '/';
}
string fullPath = _rootPath + relativePath;
string? content = await GetContentByPath(fullPath);
if (content is null)
{
context.Response.StatusCode = 404;
return;
}
Dictionary<string, string>? headers = await TryGetHeaders(fullPath);
if (headers is not null)
{
foreach (KeyValuePair<string, string> item in headers)
{
if (!item.Key.Equals("content-length", StringComparison.CurrentCultureIgnoreCase) &&
!item.Key.Equals("transfer-encoding", StringComparison.CurrentCultureIgnoreCase))
{
context.Response.Headers.TryAdd(item.Key, item.Value);
}
}
}
else
{
context.Response.ContentType = "application/json";
}
await context.Response.WriteAsync(content);
}
private Task<string?> GetContentByPath(string fullPath)
{
string contentPath = fullPath + "index.json";
if (!File.Exists(contentPath))
{
_logger.LogError("Not found content on {Path}", contentPath);
return Task.FromResult<string?>(null);
}
return File.ReadAllTextAsync(contentPath);
}
public async Task<Dictionary<string, string>?> TryGetHeaders(string fullPath)
{
string headersPath = fullPath + "headers.json";
if (File.Exists(headersPath))
{
string rawHeaders = await File.ReadAllTextAsync(headersPath);
try
{
Headers? headersObject = JsonSerializer.Deserialize(rawHeaders, AppSerializerContext.Default.Headers);
if (headersObject is not null)
{
return headersObject.Get;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ex while parse headers on {Path}", headersPath);
}
}
return null;
}
}