How Stuffle uses Docker for deploymentsRobinBrandt
Stuffle use Docker for deployments of its ruby backend since 09/2014. This presentation summarizes our experiences so far and gives an overview of the technologies we're using to manage our infrastructure.
The basic setup of the infrastructure is done via ansible. Consul is installed on every node for service discovery and application configuration. The application itself is run inside docker.
I held this short presentation at the Fourth Docker Hamburg meetup (http://www.meetup.com/Docker-Hamburg/).
This document provides an introduction and overview of Node.js. It discusses the brief history of server-side JavaScript, how Node.js was created to enable easy push capabilities for websites, and its growth in popularity in the following years. The document also covers key aspects of Node.js like non-blocking I/O, event loops, streams, modules, and dependency management with NPM. Popular frameworks like Express, Hapi, and tools/concepts like IoT, desktop apps, and real-time apps are also mentioned.
Using and scaling Rack and Rack-based middlewareAlona Mekhovova
Rack provides a standard interface between web servers and web applications. It allows a web application to return a status, headers, and a body in response to an HTTP request. Middleware can be plugged into a Rack application to modify requests and responses. Popular Rack middleware includes Rack::Cache, Rack::Middleware, and Warden for authentication. In Rails, middleware is configured through an initializer and plugged into the middleware stack to run before or after other middleware.
These are the slides for the seminar to have a basic overview on the GO Language, By Alessandro Sanino.
They were used on a Lesson in University of Turin (Computer Science Department) 11-06-2018
Exploring Async PHP (SF Live Berlin 2019)dantleech
(note slides are missing animated gifs and video)
As PHP programmers we are used to waiting for network I/O, in general we may not even consider any other option. But why wait? Why not jump on board the Async bullet-train and experience life in the fast lane and give Go and NodeJS a run for the money. This talk will aim to make the audience aware of the benefits, opportunities, and pitfalls of asynchronous programming in PHP, and guide them through the native functionality, frameworks and PHP extensions though which it can be facilitated.
This document describes the challenges of manually configuring and deploying infrastructure for Ruby on Rails and Sinatra applications. It introduces infrastructure as code using Docker and Terraform to define and deploy two microservices—a Sinatra backend and Rails frontend—to Amazon ECS. Docker is used to package each application into images to ensure consistency across environments. Terraform will configure and deploy the necessary AWS resources. Using these tools reduces manual effort and errors compared to traditional deployment methods.
Infrastructure as code: running microservices on AWS using Docker, Terraform,...Yevgeniy Brikman
This is a talk about managing your software and infrastructure-as-code that walks through a real-world example of deploying microservices on AWS using Docker, Terraform, and ECS.
This document describes the challenges of manually configuring and deploying infrastructure for Ruby on Rails and Sinatra applications. It introduces infrastructure as code using Docker and Terraform to define and deploy two microservices—a Sinatra backend and Rails frontend—to Amazon ECS. Docker is used to package each application into images to ensure consistency across environments. Terraform will configure and deploy the necessary AWS resources. Using these tools reduces manual effort and errors compared to traditional deployment methods.
June 2014 PDX PUG: Writing and Publishing Puppet Modules Puppet
The document discusses how to write and publish Puppet modules. It explains that a Puppet module encapsulates configuration for a service and includes code, files, templates, tests, and documentation. It provides guidance on module structure and content, strategies for parameterizing templates, testing modules, and publishing modules to the Forge for others to use.
1. Docker is a container platform that packages applications and dependencies to run seamlessly in any computing environment. It helps eliminate issues caused by differences in computing environments.
2. Kitematic provides a graphical user interface for Docker that makes it easy to run Docker containers without using the command line. It allows visually managing containers.
3. The Docker CLI can be used to run containers by pulling images from Docker Hub, a registry for Docker images, and using commands like docker run to launch containers from those images.
A broad introduction to Java.
What is Java and where is it used
Programming Languages in the web development
What is Java and where is it used
OOP PRINCIPLES
JAVA SE, JRE, JDK
IDE’s
Where Java used in the “Real World”
This document provides an overview and examples of using HttpURLConnection and HttpClient to communicate with HTTP servers and retrieve web pages programmatically in Android. It discusses using HttpURLConnection to open a connection to a URL and read the response stream. It also shows how to use the HttpClient class to retrieve the entire content of a URL with a single method call. The document includes code examples for searching web pages for keywords using both HttpURLConnection and HttpClient.
This presentation discusses the most neglected quality axis : code documentation. See good and bad examples, best practices on documenting code and why you should try not to ignore it :)
Presentation date: 2014-11-28
Place: Thessaloniki Java Meetup Group (SKG)
The document discusses Node.js and provides instructions for installing Node.js via different methods:
1) Homebrew can be used to install Node.js on OSX by running "brew install node.js".
2) nDistro allows creating and installing Node.js distributions within seconds by specifying module and Node binary version dependencies in a .ndistro file.
3) Node.js can be compiled from source by cloning the Node.js repository via git or downloading the source, running configuration, make, and make install commands.
Groovy is a dynamic language for the Java Virtual Machine that simplifies programming through features like closures, properties, and built-in support for lists, maps, ranges, and regular expressions. The latest version 1.5 adds support for Java 5 features like annotations and generics to leverage frameworks that use them. Groovy can be integrated into applications through mechanisms like JSR-223, Spring, and Groovy's own GroovyClassLoader to externalize business rules, provide extension points, and customize applications.
Given at TechMaine's Java Users Group on Feb 26 2008
Why do we need another build tool when we already have Ant? By focusing on convention over configuration, Maven allows you to declaratively define how your project is built, which reduces a lot of the procedural code that you'd need to implement in every build file if you were using Ant. This, along with Maven's built-in management of repositories for project dependencies, allows you to streamline your build process. Ultimately Maven can reduce the amount of time that would otherwise be wasted hunting down jar files and fiddling with boilerplate build scripts.
This presentation covers Maven's core concepts. It introduces the Plugin architecture, and explain how the most popular plugins are used. It also covers the POM concept and how it relates to dependency tracking and repositories.
Similar to Nell’iperspazio con Rocket: il Framework Web di Rust! (20)
Oltre l'hype: vulnerabilità e limiti dell'intelligenza artificiale.pdfCommit University
Non è tutto oro quello che luccica, in questa presentazione esploreremo le principali criticità e i rischi associati all'intelligenza artificiale (IA). Come si può attaccare un sistema informatico allo stesso modo esistono gli attacchi ai modelli di machine learning, come l'avvelenamento dei dati e gli esempi avversariali, che minano l'integrità dei sistemi. Inoltre, si evidenzia come i bias nei dati di addestramento possano portare a decisioni discriminatorie, influenzando settori cruciali come la giustizia e l'occupazione. La necessità di una spiegabilità nell'IA viene sottolineata per garantire trasparenza, fiducia e un uso etico della tecnologia. L'obiettivo è fornire una visione equilibrata, sottolineando l'importanza di una vigilanza continua e di miglioramenti costanti per sfruttare il potenziale dell'IA in modo responsabile.
Come funzionano i Retrieval-Augmented Generators (RAG) e quanto i database vettoriali sono fondamentali per poter memorizzare e utilizzare le sorgenti dati aziendali e personali?
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
Open source, in Python, compatibile con vari LLM ed estendibile tramite plugin: queste sono solo alcune delle potenzialità del framework Cheshire Cat AI!
Breaking REST Chains_ A Fastify & Mercurius Pathway to GraphQL Glory.pdfCommit University
This document contains slides from a presentation by Luca Del Puppo about building GraphQL servers using Fastify and Mercurius. The presentation introduces GraphQL and its advantages over REST APIs. It then discusses why Mercurius is a good choice for building GraphQL servers on Fastify and outlines some features it provides out of the box. The presentation concludes by providing resources for learning more about Fastify, Mercurius and building GraphQL servers.
Collaborazione, Decisionalità e Gestione della Complessità nel Tempo: cosa ...Commit University
Vuoi migliorare la gestione dei progetti a lungo termine con team multidisciplinari e prendere decisioni rischiose in modo sicuro e ponderato? Non perderti il nostro workshop gratuito!
Antonio Dell’Ava, Frontend Developer di eDreams Odigeo, condividerà strategie per aiutarti a ottimizzare la collaborazione nel tuo team, scegliere gli strumenti giusti per ogni situazione e garantire l’evoluzione del progetto nel tempo
A volte essere pigri è una qualità, evita (quasi) tutte le richieste di personalizzazioni lasciando "finestre aperte" nei tuoi componenti generici.
Gli slots sono un modo per passare il contenuto a un componente in Vue.js. Permettono di definire una sezione nel template di un componente che può essere sostituita dall'esterno.
È inoltre possibile assegnare un nome o uno "scope" agli slots, garantendo così maggiore controllo e personalizzazione sul contenuto. I "named slots" consentono di definire più slots nello stesso componente, assegnando dei nomi specifici.
Gli "scoped slots" ti consentono di accedere dall'esterno ai dati interni del componente.
Quante volte mi è capitato di migliorare applicazioni lente e difficili da ottimizzare, ma poi ho scoperto Qwik e tutto è cambiato.
Con il suo nuovo modello mentale è in grado di fare la differenza e scalare facilmente qualsiasi applicazione.
Non conosci questo framework? Nessuna paura...andiamo a scoprirlo assieme!
Backstage l'Internal Developer Portal Open Source per una migliore Developer ...Commit University
Backstage is an open source platform for building developer portals that unifies all tooling, services, apps, data, and documentation with a single consistent UI. It allows developers to focus on their work by providing a centralized location to create software, manage what they own, and explore the entire software ecosystem. Backstage has a customizable, extensible plugin architecture built with modern technologies to make it easy to develop for and contribute to developer portals in a cloud-agnostic, vendor-neutral way.
Nella giungla degli ORM node, Prisma sta prendendo sempre più piede. Ha migliorato la Developer Experience, si integra perfettamente con Typescript e funziona dannatamente bene con diversi provider. In questo talk, vedrai come Prisma può migliorare il tuo lavoro quotidiano e come ti permette di avere un maggior controllo della tua code base aiutandoti a prevenire fastidiosi errori nella tua applicazione nodejs.
Decision-making for Software Development Teams - Commit UniversityCommit University
Ti senti bloccato quando si tratta di prendere decisioni critiche su aspetti tecnologici? Vuoi conoscere i processi decisionali collaborativi e come applicarli al tuo team?
Francesco Strazzullo, Chief Operating Officer di Claranet Italia, ti insegnerà gli elementi chiave per prendere decisioni critiche su aspetti tecnologici, gestire i requisiti non funzionali e lavorare con processi decisionali collaborativi.
L’Advisor Leader dell’area Game di NABA, Marco Secchi, ti insegnerà come migliorare la gestione degli oggetti in-game e la loro comunicazione utilizzando Unity Engine e Design Pattern Component.
La prototipazione è un’attività fondamentale per “capire facendo”. Lo scopo della prototipazione non è costruire partendo da un progetto definito ma, piuttosto, acquisire dati preziosi per essere poi più consapevoli di prendere la giusta direzione. Alla base delle attività di prototipazione ci sono spesso strumenti low code e no code. Esistono ormai da diversi anni e ultimamente stanno guadagnando sempre più attenzione nella community per la loro immediatezza e velocità. Abbiamo definito meglio le loro qualità e le opportunità che ci sono nel loro utilizzo.
Durante il talk abbiamo approfondito perché è importante prototipare e come questa attività migliora i nostri progetti. In particolare, abbiamo approfondito l’utilizzo AWS Step Functions Workflow Studio, strumento low code prodotto da AWS. Workflow Studio ci permette di imbastire una state machine basata su step functions con uno strumento visuale drag & drop che semplifica moltissimo il nostro lavoro. Abbiamo analizzato cosa lo contraddistingue da altri strumenti e quali sono i suoi punti di forza. Infine siamo passati alla pratica facendo una piccola esercitazione con AWS Step Functions.
KMM survival guide: how to tackle struggles between Kotlin and SwiftCommit University
Kotlin Multiplatform Mobile (KMM) è un SDK per lo sviluppo di applicazioni Android ed iOS che consente agli sviluppatori di condividere la business logic mantenendo UI/UX native.
Ogni SDK/framework cross/multi platform ha i suoi pro ed i suoi contro, e purtroppo KMM non è l'eccezione che conferma la regola.
Se sei uno sviluppatore Android potresti pensare che tutto funzionerà correttamente, ma purtroppo non sarà così quando dovrai confrontarti con Swift.
Se sei uno sviluppatore iOS saprai che Swift è simile a Kotlin, ma non in tutto, dovrai quindi conoscere alcune sue caratteristiche.
In questo talk vedremo quali sono i problemi che si possono riscontrare nell'interoperabilità tra Kotlin e Swift, i motivi che li causano, e come risolverli.
Stai perdendo la testa cercando di convertire il tuo state manager da Vuex a Pinia?
Ecco una guida step-by-step per affrontare questo task senza difficoltà.
I micro-frontend sono uno degli argomenti più interessanti nel mondo frontend dell'ultimo periodo ma nonostante la loro popolarità, non esistono delle linee guida comuni per svilupparli. micro-lc risponde a questa esigenza e permette di raccogliere in un unico applicativo tanti micro-frontend, orchestrandoli e rendendoli parte della stessa applicazione e non più componenti singoli, scollegati e sconnessi.
Fastify è il web framework del momento e diverse aziende in tutto il mondo lo stanno utilizzando in produzione da anni.
Costruito da zero per essere il più veloce possibile, con un overhead minima e una potente architettura a plugin, Fastify fornisce la migliore esperienza di sviluppo, senza sacrificare prestazioni e sicurezza.
this resume for sadika shaikh bca studentSadikaShaikh7
I am a dedicated BCA student with a strong foundation in web technologies, including PHP and MySQL. I have hands-on experience in Java and Python, and a solid understanding of data structures. My technical skills are complemented by my ability to learn quickly and adapt to new challenges in the ever-evolving field of computer science.
Coordinate Systems in FME 101 - Webinar SlidesSafe Software
If you’ve ever had to analyze a map or GPS data, chances are you’ve encountered and even worked with coordinate systems. As historical data continually updates through GPS, understanding coordinate systems is increasingly crucial. However, not everyone knows why they exist or how to effectively use them for data-driven insights.
During this webinar, you’ll learn exactly what coordinate systems are and how you can use FME to maintain and transform your data’s coordinate systems in an easy-to-digest way, accurately representing the geographical space that it exists within. During this webinar, you will have the chance to:
- Enhance Your Understanding: Gain a clear overview of what coordinate systems are and their value
- Learn Practical Applications: Why we need datams and projections, plus units between coordinate systems
- Maximize with FME: Understand how FME handles coordinate systems, including a brief summary of the 3 main reprojectors
- Custom Coordinate Systems: Learn how to work with FME and coordinate systems beyond what is natively supported
- Look Ahead: Gain insights into where FME is headed with coordinate systems in the future
Don’t miss the opportunity to improve the value you receive from your coordinate system data, ultimately allowing you to streamline your data analysis and maximize your time. See you there!
The DealBook is our annual overview of the Ukrainian tech investment industry. This edition comprehensively covers the full year 2023 and the first deals of 2024.
Hire a private investigator to get cell phone recordsHackersList
Learn what private investigators can legally do to obtain cell phone records and track phones, plus ethical considerations and alternatives for addressing privacy concerns.
Data Protection in a Connected World: Sovereignty and Cyber Securityanupriti
Delve into the critical intersection of data sovereignty and cyber security in this presentation. Explore unconventional cyber threat vectors and strategies to safeguard data integrity and sovereignty in an increasingly interconnected world. Gain insights into emerging threats and proactive defense measures essential for modern digital ecosystems.
Sustainability requires ingenuity and stewardship. Did you know Pigging Solutions pigging systems help you achieve your sustainable manufacturing goals AND provide rapid return on investment.
How? Our systems recover over 99% of product in transfer piping. Recovering trapped product from transfer lines that would otherwise become flush-waste, means you can increase batch yields and eliminate flush waste. From raw materials to finished product, if you can pump it, we can pig it.
Are you interested in dipping your toes in the cloud native observability waters, but as an engineer you are not sure where to get started with tracing problems through your microservices and application landscapes on Kubernetes? Then this is the session for you, where we take you on your first steps in an active open-source project that offers a buffet of languages, challenges, and opportunities for getting started with telemetry data.
The project is called openTelemetry, but before diving into the specifics, we’ll start with de-mystifying key concepts and terms such as observability, telemetry, instrumentation, cardinality, percentile to lay a foundation. After understanding the nuts and bolts of observability and distributed traces, we’ll explore the openTelemetry community; its Special Interest Groups (SIGs), repositories, and how to become not only an end-user, but possibly a contributor.We will wrap up with an overview of the components in this project, such as the Collector, the OpenTelemetry protocol (OTLP), its APIs, and its SDKs.
Attendees will leave with an understanding of key observability concepts, become grounded in distributed tracing terminology, be aware of the components of openTelemetry, and know how to take their first steps to an open-source contribution!
Key Takeaways: Open source, vendor neutral instrumentation is an exciting new reality as the industry standardizes on openTelemetry for observability. OpenTelemetry is on a mission to enable effective observability by making high-quality, portable telemetry ubiquitous. The world of observability and monitoring today has a steep learning curve and in order to achieve ubiquity, the project would benefit from growing our contributor community.
What Not to Document and Why_ (North Bay Python 2024)Margaret Fero
We’re hopefully all on board with writing documentation for our projects. However, especially with the rise of supply-chain attacks, there are some aspects of our projects that we really shouldn’t document, and should instead remediate as vulnerabilities. If we do document these aspects of a project, it may help someone compromise the project itself or our users. In this talk, you will learn why some aspects of documentation may help attackers more than users, how to recognize those aspects in your own projects, and what to do when you encounter such an issue.
These are slides as presented at North Bay Python 2024, with one minor modification to add the URL of a tweet screenshotted in the presentation.
Implementations of Fused Deposition Modeling in real worldEmerging Tech
The presentation showcases the diverse real-world applications of Fused Deposition Modeling (FDM) across multiple industries:
1. **Manufacturing**: FDM is utilized in manufacturing for rapid prototyping, creating custom tools and fixtures, and producing functional end-use parts. Companies leverage its cost-effectiveness and flexibility to streamline production processes.
2. **Medical**: In the medical field, FDM is used to create patient-specific anatomical models, surgical guides, and prosthetics. Its ability to produce precise and biocompatible parts supports advancements in personalized healthcare solutions.
3. **Education**: FDM plays a crucial role in education by enabling students to learn about design and engineering through hands-on 3D printing projects. It promotes innovation and practical skill development in STEM disciplines.
4. **Science**: Researchers use FDM to prototype equipment for scientific experiments, build custom laboratory tools, and create models for visualization and testing purposes. It facilitates rapid iteration and customization in scientific endeavors.
5. **Automotive**: Automotive manufacturers employ FDM for prototyping vehicle components, tooling for assembly lines, and customized parts. It speeds up the design validation process and enhances efficiency in automotive engineering.
6. **Consumer Electronics**: FDM is utilized in consumer electronics for designing and prototyping product enclosures, casings, and internal components. It enables rapid iteration and customization to meet evolving consumer demands.
7. **Robotics**: Robotics engineers leverage FDM to prototype robot parts, create lightweight and durable components, and customize robot designs for specific applications. It supports innovation and optimization in robotic systems.
8. **Aerospace**: In aerospace, FDM is used to manufacture lightweight parts, complex geometries, and prototypes of aircraft components. It contributes to cost reduction, faster production cycles, and weight savings in aerospace engineering.
9. **Architecture**: Architects utilize FDM for creating detailed architectural models, prototypes of building components, and intricate designs. It aids in visualizing concepts, testing structural integrity, and communicating design ideas effectively.
Each industry example demonstrates how FDM enhances innovation, accelerates product development, and addresses specific challenges through advanced manufacturing capabilities.
Performance Budgets for the Real World by Tammy EvertsScyllaDB
Performance budgets have been around for more than ten years. Over those years, we’ve learned a lot about what works, what doesn’t, and what we need to improve. In this session, Tammy revisits old assumptions about performance budgets and offers some new best practices. Topics include:
• Understanding performance budgets vs. performance goals
• Aligning budgets with user experience
• Pros and cons of Core Web Vitals
• How to stay on top of your budgets to fight regressions
Details of description part II: Describing images in practice - Tech Forum 2024BookNet Canada
This presentation explores the practical application of image description techniques. Familiar guidelines will be demonstrated in practice, and descriptions will be developed “live”! If you have learned a lot about the theory of image description techniques but want to feel more confident putting them into practice, this is the presentation for you. There will be useful, actionable information for everyone, whether you are working with authors, colleagues, alone, or leveraging AI as a collaborator.
Link to presentation recording and transcript: https://bnctechforum.ca/sessions/details-of-description-part-ii-describing-images-in-practice/
Presented by BookNet Canada on June 25, 2024, with support from the Department of Canadian Heritage.
Quality Patents: Patents That Stand the Test of TimeAurora Consulting
Is your patent a vanity piece of paper for your office wall? Or is it a reliable, defendable, assertable, property right? The difference is often quality.
Is your patent simply a transactional cost and a large pile of legal bills for your startup? Or is it a leverageable asset worthy of attracting precious investment dollars, worth its cost in multiples of valuation? The difference is often quality.
Is your patent application only good enough to get through the examination process? Or has it been crafted to stand the tests of time and varied audiences if you later need to assert that document against an infringer, find yourself litigating with it in an Article 3 Court at the hands of a judge and jury, God forbid, end up having to defend its validity at the PTAB, or even needing to use it to block pirated imports at the International Trade Commission? The difference is often quality.
Quality will be our focus for a good chunk of the remainder of this season. What goes into a quality patent, and where possible, how do you get it without breaking the bank?
** Episode Overview **
In this first episode of our quality series, Kristen Hansen and the panel discuss:
⦿ What do we mean when we say patent quality?
⦿ Why is patent quality important?
⦿ How to balance quality and budget
⦿ The importance of searching, continuations, and draftsperson domain expertise
⦿ Very practical tips, tricks, examples, and Kristen’s Musts for drafting quality applications
https://www.aurorapatents.com/patently-strategic-podcast.html
The Rise of Supernetwork Data Intensive ComputingLarry Smarr
Invited Remote Lecture to SC21
The International Conference for High Performance Computing, Networking, Storage, and Analysis
St. Louis, Missouri
November 18, 2021
2. WHO AM I
Denny Biasiolli
Full Stack Developer
(JavaScript, Python, Go, Rust)
Front End Developer UX/ UI
Fingerprint Compliance Services Ltd
Italy, Savigliano (CN)
@dennybiasiolli
denny.biasiolli@gmail.com
www.dennybiasiolli.com
2
10. ROCKET AIMS TO BE FUN
By ensuring that you write as little code
as possible to accomplish your task.
Allows you to focus on the fun parts of
writing web applications.
10
11. ROCKET CORE PHILOSOPHIES
Security, correctness, and developer experience
are paramount.
The path of least resistance should lead you to the most secure, correct web application,
though security and correctness should not come at the cost of a degraded developer
experience.
Rocket is easy to use while taking great measures to ensure that your application is secure
and correct without cognitive overhead.
11
12. ROCKET CORE PHILOSOPHIES
All request handling information
should be typed and self-contained.
Because the web and HTTP are themselves untyped (or stringly typed, as some call it), this
means that something or someone has to convert strings to native types.
Rocket does this for you with zero programming overhead.
What's more, Rocket's request handling is self-contained with zero global state: handlers
are regular functions with regular arguments.
12
13. ROCKET CORE PHILOSOPHIES
Decisions should not be forced.
Templates, serialization, sessions, and just about everything else are all pluggable, optional
components.
While Rocket has official support and libraries for each of these, they are completely
optional and swappable.
13
18. HELLO, WORLD!
> cargo run
🔧 Configured for debug.
>> address: 127.0.0.1
>> port: 8000
>> workers: [..]
>> keep-alive: 5s
>> limits: [..]
>> tls: disabled
>> temp dir: /tmp
>> log level: normal
>> cli colors: true
🛰 Routes:
>> (index) GET /
🚀 Rocket has launched from http://127.0.0.1:8000
18
19. But wait, what's this?
Error: Rocket failed to bind network socket to
given address/port.
>> Address already in use (os error 48)
19
20. Rocket.toml FILE
## defaults for all profiles
[default]
port = 8000
## set only when compiled in debug mode,
## i.e, `cargo build` or `cargo run`
[debug]
port = 8001
https://rocket.rs/guide/v0.5/configuration/
20
21. Rocket.toml FILE
## set only when the `custom-profile` profile is selected,
## i.e, `ROCKET_PROFILE=custom-profile cargo build --release`
[custom-profile]
port = 9001
## set only when compiled in release mode,
## i.e, `cargo build --release`
[release]
port = 9999
https://rocket.rs/guide/v0.5/configuration/
21
22. ENVIRONMENT VARIABLES
Take precedence over Rocket.toml file.
Even at runtime.
ROCKET_PORT=8007 cargo run
https://rocket.rs/guide/v0.5/configuration/
22
26. ROCKET LIFECYCLE
3. Processing
#[get("/hello/<name>")]
fn hello(name: &str, age: u8) -> String {
/**
* Processing
* i.e, checking the age range, etc.
* This is the main business logic of an application.
* Processing completes by returning a Response.
*/
format!("Hello, {} year old named {}!", age, name)
}
26
29. LAUNCHING
allows you to start the server
is useful when a handle to the Future returned by launch() is desired
or when the return value of launch() is to be inspected.
#[rocket::main]
async fn main() -> Result<(), rocket::Error> {
let _rocket = rocket::build()
.mount("/hello", routes![world])
.launch()
.await?;
Ok(())
}
29
31. DYNAMIC PATHS
Any type, as long as the type implements the
FromParam trait.
#[get("/hello/<name>/<age>/<cool>")]
fn hello(name: &str, age: u8, cool: bool) -> String {
if cool {
format!("You're a cool {} year old, {}!", age, name)
} else {
format!(
"{}, we need to talk about your coolness.",
name
)
}
}
31
33. SERVE STATIC FILES
The easy way
use rocket::fs::FileServer;
// use rocket::fs::{relative, FileServer};
#[launch]
fn rocket() -> _ {
rocket::build()
// serve files from `/www/static` at path `/public`
.mount("/public", FileServer::from("/www/static"))
// or `relative!("static")` for a local directory
}
33
35. HTTP METHODS
What about HTML forms?
Form method="post"
Content-Type: application/x-www-form-urlencoded
First field name="_method"
First field value="<a valid HTTP method>"
<form action="/your/path" method="post">
<input type="hidden" name="_method" value="put" />
<!-- other fields -->
35
40. TEMPLATES
Rocket discovers templates in the configurable
template_dir directory.
Templating support in Rocket is engine agnostic.
The engine used to render a template depends on the
template file's extension.
if a file ends with .hbs, Handlebars is used
if a file ends with .tera, Tera is used
40
41. TERA TEMPLATES
Note: The name of the template does not include its
extension.
For a template file named index.html.tera, call
render("index") and use the name "index" in
templates, i.e, extends "index" or extends
"base" for base.html.tera.
41
42. TERA TEMPLATES
Tera is a template engine inspired by Jinja2 and the Django template language.
https://keats.github.io/tera/
<title>{% block title %}{% endblock title %}</title>
<ul>
{% for user in users %}
<li><a href="{{ user.url }}">{{ user.username }}</a></li>
{% endfor %}
</ul>
42
43. REQUEST GUARDS
Types that implement the FromRequest trait
Used to extract data from the request
Can be used as arguments in request handlers
Protect a handler from being called erroneously
#[get("/<param>")]
fn index(param: isize, a: A, b: B, c: C) { /* ... */ }
// `A`, `B`, and `C` are request guards
https://api.rocket.rs/v0.5/rocket/request/trait.FromRequest
43
48. 🍪COOKIES?
use rocket::form::Form;
use rocket::response::Redirect;
use rocket::http::CookieJar;
#[post("/", data = "<message>")]
fn submit(cookies: &CookieJar<'_>, message: Form<&str>) -> Red
cookies.add(("message", message.to_string()));
Redirect::to(uri!(index))
}
#[get("/")]
fn index(cookies: &CookieJar<'_>) -> Option<String> {
cookies.get("message")
.map(|crumb| format!("Message: {}", crumb.value()))
}
48
49. 🍪PRIVATE COOKIES?
1. make sure the "secrets" feature is enabled
2. add "_private" to "add", "get" and "remove"
Encrypted using the 256-bit key specified in the
secret_key configuration parameter.
## in Cargo.toml
rocket = { version = "0.5.0", features = ["secrets
cookies.get_private
cookies.add_private
cookies.remove_private
49
50. FORM INPUT? YES, PLEASE!
Rocket supports both
"multipart" and "x-www-form-urlencoded" forms
out of the box,
enabled by the Form data guard
and derivable FromForm trait.
https://rocket.rs/guide/v0.5/requests/#forms
50
52. FORM INPUT
curl --location 'http://127.0.0.1:8001/todo'
--form 'description="test"'
--form 'complete="true"'
curl --location 'http://127.0.0.1:8001/todo'
--header 'Content-Type: application/x-www-form-urlencoded'
--data-urlencode 'description=test'
--data-urlencode 'complete=true'
# or
# Output form errors with:
# 422 Unprocessable Entity
# or
# 415 Unsupported Media Type
52
53. QUERY PARAMS? YES, PLEASE!
Query strings are URL-encoded forms
that appear in the URL of a request.
Query parameters are declared like path parameters
but otherwise handled like regular URL-encoded form
fields.
https://rocket.rs/guide/v0.5/requests/#query-strings
53
56. JSON INPUT? YES, PLEASE!
Make sure the "json" feature is enabled
The Json<T> guard deserializes body data as JSON.
The only condition is that the generic type T
implements the Deserialize trait from serde.
## in Cargo.toml
rocket = { version = "0.5.0", features = ["json"] }
https://rocket.rs/guide/v0.5/requests/#json
56
63. MANAGED (GLOBAL) STATE
The state is managed on a per-type basis
1. Call manage on the Rocket instance corresponding
to your application with the initial value of the state.
use std::sync::atomic::AtomicUsize;
struct HitCount {
count: AtomicUsize
}
rocket::build()
.manage(HitCount { count: AtomicUsize::new(0) });
63
64. MANAGED (GLOBAL) STATE
2. Add a &State<T> type to any request handler,
where T is the type of the value passed into manage.
use rocket::State;
#[get("/count")]
fn count(hit_count: &State<HitCount>) -> String {
let current_count = hit_count.count.load(Ordering::Rela
format!("Number of visits: {}", current_count)
}
64
65. REQUEST-LOCAL STATE
use rocket::request::{self, Request, FromRequest};
/// A global atomic counter for generating IDs.
static ID_COUNTER: AtomicUsize = AtomicUsize::new(0);
/// A type that represents a request's ID.
struct RequestId(pub usize);
#[get("/")]
fn id(id: &RequestId) -> String {
format!("This is request #{}.", id.0)
}
65
66. REQUEST-LOCAL STATE
/// Returns the current request's ID,
/// assigning one only as necessary.
#[rocket::async_trait]
impl<'r> FromRequest<'r> for &'r RequestId {
type Error = ();
async fn from_request(request: &'r Request<'_>)
-> request::Outcome<Self, Self::Error> {
// The closure passed to `local_cache`
// will be executed at most once per request:
// When requested again, will return the same value.
request::Outcome::Success(request.local_cache(|| {
RequestId(ID_COUNTER.fetch_add(1, Ordering::Relaxe
}))
}
66
67. DATABASES
Rocket includes built-in, ORM-agnostic support for
databases via rocket_db_pools.
The library simplifies accessing one or more databases
via connection pools: data structures that maintain
active database connections for use in the application.
cargo add rocket_db_pools --features "sqlx_sqlite"
# or
cargo add rocket_db_pools --features "sqlx_postgres"
# or
cargo add rocket_db_pools --features "diesel_postgres"
https://api.rocket.rs/v0.5/rocket_db_pools/#supported-drivers
67
68. DATABASES
Configure at least a URL for the database under
databases.$name (in Rocket.toml), where $name is
your choice of database name:
[default.databases.custom_name]
url = "database.sqlite"
[default.databases.custom_name_postgres]
url = "postgresql://[user[:password]@][host][:port][/dbname]"
68