-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHandlers.cs
40 lines (33 loc) · 1.35 KB
/
Handlers.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
using System.Text.Json;
using OpenTelemetry.Trace;
namespace TracingWeb;
public static class Handlers
{
private static readonly JsonSerializerOptions jsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
public static async Task<IResult> HandleAllPosts(Tracer tracer, IHttpClientFactory httpFactory)
{
using var span = tracer.StartActiveSpan("all-posts");
var result = Enumerable.Empty<Post>();
using (tracer.StartActiveSpan("http-request"))
{
var httpClient = httpFactory.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "https://jsonplaceholder.typicode.com/posts");
var response = await httpClient.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
span.AddEvent("Error while making http request.");
return Results.Problem();
}
using (tracer.StartActiveSpan("serializing-response"))
{
using var contentStream = await response.Content.ReadAsStreamAsync();
result = await JsonSerializer.DeserializeAsync<IEnumerable<Post>>(contentStream, jsonOptions) ?? result;
}
}
span.SetAttribute("post-count", result.Count());
return Results.Ok(result);
}
}