forked from microsoft/OpenAPI.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDefaultStreamLoader.cs
More file actions
56 lines (51 loc) · 2.16 KB
/
DefaultStreamLoader.cs
File metadata and controls
56 lines (51 loc) · 2.16 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
using System.IO;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Models;
namespace Microsoft.OpenApi.Reader.Services
{
/// <summary>
/// Implementation of IInputLoader that loads streams from URIs
/// </summary>
public class DefaultStreamLoader : IStreamLoader
{
private readonly HttpClient _httpClient;
/// <summary>
/// The default stream loader
/// </summary>
/// <param name="httpClient">The HttpClient to use to retrieve documents when needed</param>
public DefaultStreamLoader(HttpClient httpClient)
{
_httpClient = Utils.CheckArgumentNull(httpClient);
}
/// <inheritdoc/>
public async Task<Stream> LoadAsync(Uri baseUrl, Uri uri, CancellationToken cancellationToken = default)
{
var absoluteUri = (baseUrl.AbsoluteUri.Equals(OpenApiConstants.BaseRegistryUri), baseUrl.IsAbsoluteUri, uri.IsAbsoluteUri) switch
{
(true, _, _) => new Uri(Path.Combine(Directory.GetCurrentDirectory(), uri.ToString())),
// this overcomes a URI concatenation issue for local paths on linux OSes
(_, true, false) when baseUrl.Scheme.Equals("file", StringComparison.OrdinalIgnoreCase) && !RuntimeInformation.IsOSPlatform(OSPlatform.Windows) =>
new Uri(Path.Combine(baseUrl.AbsoluteUri, uri.ToString())),
(_, _, _) => new Uri(baseUrl, uri),
};
return absoluteUri.Scheme switch
{
"file" => File.OpenRead(absoluteUri.AbsolutePath),
"http" or "https" =>
#if NET5_0_OR_GREATER
await _httpClient.GetStreamAsync(absoluteUri, cancellationToken).ConfigureAwait(false),
#else
await _httpClient.GetStreamAsync(absoluteUri).ConfigureAwait(false),
#endif
_ => throw new ArgumentException("Unsupported scheme"),
};
}
}
}