2
0

Add zstd compression to all API Traffic

This commit is contained in:
Glax 2024-10-31 22:16:18 +01:00
parent f7daacf0d4
commit b7bc04a045
3 changed files with 15 additions and 8 deletions

View File

@ -91,6 +91,7 @@ That is why I wanted to create my own project, in a language I understand, and t
- [Html Agility Pack (HAP)](https://html-agility-pack.net/)
- [Soenneker.Utils.String.NeedlemanWunsch](https://github.com/soenneker/soenneker.utils.string.needlemanwunsch)
- [Sixlabors.ImageSharp](https://docs-v2.sixlabors.com/articles/imagesharp/index.html#license)
- [zstd-wrapper](https://github.com/oleg-st/ZstdSharp) [zstd](https://github.com/facebook/zstd)
- 💙 Blåhaj 🦈
<p align="right">(<a href="#readme-top">back to top</a>)</p>

View File

@ -5,6 +5,7 @@ using System.Text.RegularExpressions;
using Newtonsoft.Json;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Png;
using ZstdSharp;
namespace Tranga.Server;
@ -205,32 +206,36 @@ public partial class Server : GlobalBase, IDisposable
response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
response.AddHeader("Access-Control-Allow-Methods", "GET, POST, DELETE");
response.AddHeader("Access-Control-Max-Age", "1728000");
response.AppendHeader("Access-Control-Allow-Origin", "*");
response.AddHeader("Access-Control-Allow-Origin", "*");
response.AddHeader("Content-Encoding", "zstd");
using CompressionStream compressor = new (response.OutputStream, 5);
try
{
if (content is Stream stream)
{
response.ContentType = "text/plain";
stream.CopyTo(response.OutputStream);
response.AddHeader("Cache-Control", "no-store");
stream.CopyTo(compressor);
stream.Close();
}else if (content is Image image)
{
response.ContentType = image.Metadata.DecodedImageFormat?.DefaultMimeType ?? PngFormat.Instance.DefaultMimeType;
response.AddHeader("Cache-Control", "max-age=600");
image.Save(response.OutputStream, image.Metadata.DecodedImageFormat ?? PngFormat.Instance);
image.Save(compressor, image.Metadata.DecodedImageFormat ?? PngFormat.Instance);
image.Dispose();
}
else
{
response.ContentType = "application/json";
response.AddHeader("Cache-Control", "no-store");
response.OutputStream.Write(content is not null
? Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(content))
: Array.Empty<byte>());
if(content is not null)
new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(content))).CopyTo(compressor);
else
compressor.Write(Array.Empty<byte>());
}
compressor.Flush();
response.OutputStream.Close();
}
catch (HttpListenerException e)

View File

@ -16,6 +16,7 @@
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.5" />
<PackageReference Include="Soenneker.Utils.String.NeedlemanWunsch" Version="2.1.301" />
<PackageReference Include="System.Drawing.Common" Version="9.0.0-preview.7.24405.4" />
<PackageReference Include="ZstdSharp.Port" Version="0.8.1" />
</ItemGroup>
<ItemGroup>