https://kotlinlang.org logo
Title
s

strindberg

05/26/2023, 10:03 AM
I am trying to run a Ktor server without using an `application.conf`file, but I find no way of configuring the `rootPath`when using
embeddedServer
. This snippet compiles, but does not affect the root path - the application still uses
/
as root path: fun main() { embeddedServer( Netty, port = 8097, configure = { applicationEngineEnvironment { rootPath = "/api" } }, module = Application::main ).start(wait = true) } Does anyone know it it's possible to configure
rootPath
when using
embeddedServer?
a

Aleksei Tirman [JB]

05/26/2023, 11:47 AM
The
rootPath
property is only applied for the servlet containers. What behavior do you expect with the above code?
s

strindberg

05/26/2023, 12:43 PM
Well, when running through EngineMain, I can configure `rootPath`to "/api", and all endpoint paths within my application will have the prefix "/api", i.e. I can specify a route "/users", and it will be available for requests at "/api/users" . I wanted to do the same, but with embeddedServer.
d

david dereba

05/26/2023, 5:04 PM
If am am getting you right @strindberg, to achieve that you need to do something like this routing { route("/users"){ post("/add") { val requestUser = call.receive<User>() val userId = UserDao.addUser(requestUser.name) val newUser = User(userId, requestUser.name) call.respond(HttpStatusCode.Created, newUser) } I hope this helps
s

strindberg

05/26/2023, 7:44 PM
Thank you David, but my problem is not with the implementation of my route. What I want to achieve is for all rest paths to have the prefix "/api", without having to specify if for every endpoint. This can be achieved when running through EngineMain, configuring it in
application.conf
, but I can find no way of doing the same kind of configuration in EmbeddedServer.
d

david dereba

05/27/2023, 9:48 AM
I now understand you @strindberg, but from my side have not tried implementing that before and I should try but in the meantime, I hope you will find someone who has a solution, thanks.
a

Aleksei Tirman [JB]

05/29/2023, 9:09 AM
@strindberg the problem is that you've configured the server incorrectly. Here is a correct way:
embeddedServer(
    Netty,
    applicationEngineEnvironment {
        rootPath = "/api"
        connector {
            port = 8097
        }
        module(Application::main)
    }
).start(wait = true)
s

strindberg

05/29/2023, 11:29 AM
@Aleksei Tirman [JB] Thank you! That solved my problem.