private Result <List <KeyValue> > GetKeyValuesFromConsul(string name) { // Default lookup key is actual key preceded by default folder prefix var key = KeyUtilities.GetDefaultLookupKey(name); try { var keyVal = KeyValue.Create(key); // Get the URL to call. Use ?recurse to get any potential matches var url = $"{consulUri.CombineWith(keyVal.ToGetUrl())}?recurse"; log.Debug($"Calling {url} to get values"); var result = url.SendStringToUrl("GET", accept: "application/json"); // Consul KV always returns a collection var keyValues = result.FromJson <List <KeyValue> >(); return(keyValues.Count == 0 ? Result <List <KeyValue> > .Fail() : Result <List <KeyValue> > .Success(keyValues)); } catch (Exception ex) { log.Error($"Error getting config value with key {key}", ex); return(Result <List <KeyValue> > .Fail()); } }
/// <inheritdoc /> public virtual void Set <T>(string key, T value) { key.ThrowIfNullOrEmpty(nameof(key)); var setKey = KeyUtilities.GetKeyForSpecificity(key, setSpecificity); log.Debug($"Key {setKey} will be used for setting value for provided key: {key}"); var keyVal = KeyValue.Create(setKey, value); string result; try { result = consulUri.CombineWith(keyVal.ToPutUrl()).PutJsonToUrl(keyVal.Value); } catch (Exception ex) { var message = $"Error setting value {value} to configuration {key}. SetKey: {setKey}"; log.Error(message, ex); throw new ConfigurationErrorsException($"Error setting configuration key {setKey}", ex); } // Consul returns true|false to signify success bool success; if (!bool.TryParse(result, out success) || !success) { log.Warn($"Error setting value {value} to configuration {key}. SetKey: {setKey}"); throw new ConfigurationErrorsException($"Error setting configuration key {setKey}"); } }
private Result <T> GetValue <T>(string name) { var resultValues = GetKeyValuesFromConsul(name); if (!resultValues.IsSuccess) { return(Result <T> .Fail()); } var kv = KeyUtilities.GetMostSpecificMatch(resultValues.Value, name); try { return(Result <T> .Success(kv.GetValue <T>())); } catch (NotSupportedException ex) { log.Error($"Unable to deserialise config value with key {name}", ex); return(Result <T> .Fail()); } catch (SerializationException ex) { log.Error($"Unable to deserialise config value with key {name}", ex); return(Result <T> .Fail()); } }