using Salmon.Core; using Salmon.Core.Cliff; using System.Diagnostics; namespace Salmon.Model.Monitor; public class WebEndpoint : Element { [PersistentField] public bool Joinable { get; set; } = true; [PersistentField] public string? Uri { get; set; } [PersistentField] public string? Method { get; set; } [PersistentField] public int? Code { get; set; } [PersistentField] public string? Content { get; set; } public bool Ok { get { return Joinable && (Code != null && Code >= 200 && Code < 300); } } protected WebEndpoint() { } public WebEndpoint(string identifier) : base(identifier) { } public override IEnumerable> ImportantProperties() { foreach (var kv in base.ImportantProperties()) yield return kv; if (Uri is not null) yield return new KeyValuePair(nameof(Uri), Uri); if (Method is not null) yield return new KeyValuePair(nameof(Method), Method); yield return new KeyValuePair(nameof(Ok), Ok); if (Code is not null) yield return new KeyValuePair(nameof(Code), Code); } public static async Task From(string uri, string method = "GET", string? id = null) { if(id is null) id = Helper.CreateIdFrom("webendpoint", uri, method); using HttpClient client = new(); HttpMethod httpmethod = new(method); HttpRequestMessage request = new(httpmethod, uri); HttpResponseMessage response; var ret = new WebEndpoint(id) { Uri = uri, Method = method }; try { response = await client.SendAsync(request); } catch(Exception e) { ret.Joinable = false; ret.Content = e.ToString(); return ret; } ret.Code = (int)response.StatusCode; ret.Content = response.Content.ToString(); return ret; } }