Config::url() to get full URL of server (either as Websocket or HTTP)

This commit is contained in:
Mike Dilger 2024-06-26 12:06:24 +12:00
parent 5b2f8b5669
commit 1c608ab1bf
2 changed files with 49 additions and 0 deletions

View File

@ -1,4 +1,5 @@
use crate::error::Error;
use hyper::http::uri::{Authority, Scheme, Uri};
use pocket_types::Pubkey;
use serde::{Deserialize, Serialize};
use std::str::FromStr;
@ -194,3 +195,19 @@ impl Default for Config {
friendly.into_config().unwrap()
}
}
impl Config {
pub fn url(&self, inner: Uri, http: bool) -> Result<Uri, Error> {
let mut uri_parts = inner.into_parts();
let scheme = match (self.use_tls, http) {
(false, false) => Scheme::from_str("ws").unwrap(),
(true, false) => Scheme::from_str("wss").unwrap(),
(false, true) => Scheme::HTTP,
(true, true) => Scheme::HTTPS,
};
uri_parts.scheme = Some(scheme);
let authority = Authority::from_str(&format!("{}:{}", self.hostname, self.port))?;
uri_parts.authority = Some(authority);
Ok(Uri::from_parts(uri_parts)?)
}
}

View File

@ -58,6 +58,12 @@ pub enum ChorusError {
// Hyper
Hyper(hyper::Error),
// Invalid URI
InvalidUri(hyper::http::uri::InvalidUri),
// Invalid URI Parts
InvalidUriParts(hyper::http::uri::InvalidUriParts),
// I/O
Io(std::io::Error),
@ -134,6 +140,8 @@ impl std::fmt::Display for ChorusError {
ChorusError::EventIsInvalid(s) => write!(f, "Event is invalid: {s}"),
ChorusError::Http(e) => write!(f, "{e}"),
ChorusError::Hyper(e) => write!(f, "{e}"),
ChorusError::InvalidUri(e) => write!(f, "{e}"),
ChorusError::InvalidUriParts(e) => write!(f, "{e}"),
ChorusError::Io(e) => write!(f, "{e}"),
ChorusError::MissingTable(t) => write!(f, "Missing table: {t}"),
ChorusError::NoPrivateKey => write!(f, "Private Key Not Found"),
@ -167,6 +175,8 @@ impl StdError for ChorusError {
ChorusError::Crypto(e) => Some(e),
ChorusError::Http(e) => Some(e),
ChorusError::Hyper(e) => Some(e),
ChorusError::InvalidUri(e) => Some(e),
ChorusError::InvalidUriParts(e) => Some(e),
ChorusError::Io(e) => Some(e),
ChorusError::PocketDb(e) => Some(e),
ChorusError::PocketDbHeed(e) => Some(e),
@ -197,6 +207,8 @@ impl ChorusError {
ChorusError::EventIsInvalid(_) => 0.2,
ChorusError::Http(_) => 0.0,
ChorusError::Hyper(_) => 0.0,
ChorusError::InvalidUri(_) => 0.0,
ChorusError::InvalidUriParts(_) => 0.0,
ChorusError::Io(_) => 0.0,
ChorusError::MissingTable(_) => 0.0,
ChorusError::NoPrivateKey => 0.0,
@ -298,6 +310,26 @@ impl From<hyper::Error> for Error {
}
}
impl From<hyper::http::uri::InvalidUri> for Error {
#[track_caller]
fn from(err: hyper::http::uri::InvalidUri) -> Self {
Error {
inner: ChorusError::InvalidUri(err),
location: std::panic::Location::caller(),
}
}
}
impl From<hyper::http::uri::InvalidUriParts> for Error {
#[track_caller]
fn from(err: hyper::http::uri::InvalidUriParts) -> Self {
Error {
inner: ChorusError::InvalidUriParts(err),
location: std::panic::Location::caller(),
}
}
}
impl From<std::io::Error> for Error {
#[track_caller]
fn from(err: std::io::Error) -> Self {