Rust restAPI - using rocket and postgreSQL

hello, I want to create restAPI using rocket and postgreSQL as database, I have successfully create the connection and fetch data from database, My question is how to make something like global variable that could wrap the connection, so every routes could use it, so the database connection just called once, ? My example code on github: learn_rust/rocket_postgresql.rs at main · delcode92/learn_rust · GitHub

You are probably looking for State. The docs describing State can be found here, with a subsection about databases in particular.

2 Likes

thanks, I have try using rocket::state . My db_connection is wrapped in a struct field, then those struct I manage as a state, So I could call it on any routes.
image
for complete code I made : learn_rust/rust_state.rs at main · delcode92/learn_rust · GitHub

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.