Laservall_solidworks_inject/Server/StaticFileHandler.cs

83 lines
2.9 KiB
C#
Raw Permalink Normal View History

using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Laservall.Solidworks.Server
{
internal static class StaticFileHandler
{
private const string ResourceName = "Laservall.Solidworks.Resources.index.html";
public static async Task ServeIndex(HttpListenerContext context, string authToken, CancellationToken ct)
{
byte[] html = GetIndexHtml(authToken);
if (html == null)
{
context.Response.StatusCode = 500;
byte[] err = Encoding.UTF8.GetBytes("SPA resource not found");
context.Response.ContentLength64 = err.Length;
await context.Response.OutputStream.WriteAsync(err, 0, err.Length, ct);
context.Response.Close();
return;
}
context.Response.StatusCode = 200;
context.Response.ContentType = "text/html; charset=utf-8";
context.Response.ContentLength64 = html.Length;
context.Response.Headers.Set("Cache-Control", "no-cache, no-store, must-revalidate");
await context.Response.OutputStream.WriteAsync(html, 0, html.Length, ct);
context.Response.Close();
}
private static byte[] GetIndexHtml(string authToken)
{
var assembly = Assembly.GetExecutingAssembly();
using (var stream = assembly.GetManifestResourceStream(ResourceName))
{
if (stream == null)
{
return GetPlaceholderHtml();
}
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
string html = reader.ReadToEnd();
html = html.Replace("{AUTH_TOKEN}", authToken);
return Encoding.UTF8.GetBytes(html);
}
}
}
private static byte[] GetPlaceholderHtml()
{
string html = @"<!DOCTYPE html>
<html lang=""zh-CN"">
<head>
<meta charset=""utf-8"" />
<title>BOM </title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
display: flex; align-items: center; justify-content: center;
height: 100vh; margin: 0; background: #f5f5f5; color: #333; }
.placeholder { text-align: center; }
.placeholder h1 { font-size: 24px; margin-bottom: 8px; }
.placeholder p { color: #999; }
code { background: #e8e8e8; padding: 2px 6px; border-radius: 3px; font-size: 13px; }
</style>
</head>
<body>
<div class=""placeholder"">
<h1>BOM </h1>
<p>SPA <code>npm run build</code> </p>
</div>
</body>
</html>";
return Encoding.UTF8.GetBytes(html);
}
}
}