Passing state variable to handler functions

A general question about Julia web frameworks like Oxygen.jl: Is there an easy way to pass a state variable as an argument to handler functions, or is relying on global variables the only option?

Hi @ehsani63,

Sorry about the very late response but for future readers there is an easy way to do this using
Application Context

Below is an excerpt from the docs:


Most applications at some point will need to rely on some shared global state across the codebase. This usually comes in the form of a shared database connection pool or some other in memory store. Oxygen provides a context argument which acts as a free spot for developers to store any objects that should be available throughout the lifetime of an application.

There are three primary ways to get access to your application context

  • Injected into any request handler using the Context struct.
  • The context keyword argument in a function handler
  • Through the context() function

There are no built-in data race protections, but this is intentional. Not all applications have the same requirements, so it’s up to the developer to decide how to best handle this. For those who need to share mutable state across multiple threads I’d recommend looking into using Actors, Channels, or ReentrantLocks to handle this quickly.

Below is a simplified example where we store a Person as the application context to show how things are connected and shared.

using Oxygen

struct Person
    name::String
end

# The ctx argument here is injected through the Context class
@get "/ctx-injection" function(req, ctx::Context{Person})
    person :: Person = ctx.payload # access the underlying value
    return "Hello $(person.name)!"
end

# Access the context through the 'context' keyword argument 
@get "/ctx-kwarg" function(req; context)
    person :: Person = context 
    return "Hello $(person.name)!"
end

# Access context through the 'context()' function
@get "/ctx-function" function(req)
    person :: Person = context()
    return "Hello $(person.name)!"
end

# This represents the application context shared between all handlers
person = Person("John")

# Here is how we set the application context in our server
serve(context=person)
1 Like