93 lines
2.1 KiB
C#
93 lines
2.1 KiB
C#
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<KeyValuePair<string, object>> ImportantProperties()
|
|
{
|
|
foreach (var kv in base.ImportantProperties())
|
|
yield return kv;
|
|
|
|
if (Uri is not null)
|
|
yield return new KeyValuePair<string, object>(nameof(Uri), Uri);
|
|
|
|
if (Method is not null)
|
|
yield return new KeyValuePair<string, object>(nameof(Method), Method);
|
|
|
|
yield return new KeyValuePair<string, object>(nameof(Ok), Ok);
|
|
|
|
if (Code is not null)
|
|
yield return new KeyValuePair<string, object>(nameof(Code), Code);
|
|
}
|
|
|
|
public static async Task<WebEndpoint> 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;
|
|
}
|
|
}
|