validation done by parse and safeApply functions of Uri
Hi,
I cannot understand the parse and safeApply functions of Uri
The following unit tests are OK. import sttp.model.Uri // scheme:[//[user:password@]host[:port]]path[?query][#fragment] assert(Uri.safeApply("http://example.com/path?query=123#frag").isRight) assert(Uri.safeApply("mailto:[email protected]").isRight) assert(Uri.safeApply("ftp://user:[email protected]:21/files").isRight)
But the following unit tests are KO : do I use correctly the API to validate an uri ? // 1. Missing scheme assert(Uri.safeApply("example.com/path").isLeft) // 2. Invalid characters (unescaped) assert(Uri.safeApply("http://example.com/space here").isLeft) // 3. Invalid port number assert(Uri.safeApply("http://example.com:999999/path").isLeft) // 4. Malformed IPv6 address assert(Uri.safeApply("http://[2001:db8::12345]/path").isLeft)
regards,
OD
So the safeApply methods create URIs from the given components - host, port, path etc. The single-argument safeApply takes a host. There are other variants, as well:
def safeApply(host: String): Either[String, Uri] = ...
def safeApply(host: String, port: Int): Either[String, Uri] = ...
def safeApply(host: String, port: Int, path: Seq[String]): Either[String, Uri] = ...
...
Take a look in the Uri companion object.
The method you're looking for is probably .parse, which also returns an Either. However, when using the method the results are also Rights:
Uri.parse("example.com/path") -> scheme is optional, so this is a valid URI
Uri.parse("http://example.com/space here") -> the parser is lenient here, we don't verify that there are unallowed characters. When re-encoded, you'll get a %20 instead of the space
Uri.parse("http://example.com:999999/path") -> we don't validate the port number. Is that part of the URI spec?
Uri.parse("http://[2001:db8::12345]/path") -> same, we don't validate the IP (either v4 or v6). Once again, I'm not sure if that's part of the spec (but maybe it is).
What we do validate are gross violations of the URI syntax - cases when the parser wouldn't be able to proceed.