I have a plain old java-library gradle module. In ...
# squarelibraries
c
I have a plain old java-library gradle module. In this module I'm making use of mockhttpserver from okhttp and I'm just hardcoding responses to api calls. Everything is working great. I have this
Copy code
path == "/api/myendpoint" -> {
    return MockResponse()
        .setResponseCode(200)
        .setBody(
            """
            {"status":0,"message":"SUCCESS"}
            """.trimIndent())
}
I now want to take this json, place it into
resources/json/myendpoint.json
and read it from the file instead of having large json snippets in my kotlin code. As an end result I'd love to be able to do this but I'm a bit in over my head in terms of grabbing a resource and converting it to a string. There seems to be like 1000 different ways to do this via SO and from what I would expect... maybe there's an easy way to do this with okhttp/mockwebserver/okio that I'm missing?
Copy code
path == "/api/myendpoint" -> {
    return MockResponse()
        .setResponseCode(200)
        .setBody(javaClass.classLoader.getResourceAsStream("json/myendpoint.json").toString())
}
e
FYI I'm pretty sure you don't mean
.toString()
there, it'll return the String form of the InputStream…
c
Yeah sorry I guess I worded my question incorrectly. I'm trying to say that
Copy code
javaClass.classLoader.getResourceAsStream("json/myendpoint.json").toString()
is pseudo code so-to-speak, but is there an easy way to just convert it to a string via some kind of okhttp/okio helpers?
e
.getResource("META-INF/MANIFEST.MF").readText()
would work
there is a okio.internal.ResourceFileSystem available via
FileSystem.RESOURCES
c
NICE! I wasn't far off with my original thought. I can confirm that
Copy code
javaClass.classLoader.getResource("json/myendpoint.json").readText()
worked!
e
I don't currently have okio alpha but I expect something like
Copy code
FileSystem.RESOURCES.read("json/myendpoint.json".toPath()) { readUtf8() }
to work equivalently
yep, confirmed on 3.0.0-alpha.9
c
Cool. Looks like I will go this route. It'd be nice to get some type safety on those files, instead of being stringly typed... but oh well
e
https://github.com/icerockdev/moko-resources does generate code for access to resources but I dunno if it works outside of Android/iOS projects (never tried it)
👍 1
but honestly I find string typing ok in tests… if they fail it's not like it's not covered by a test 😄
☝️ 2