SlideShare a Scribd company logo
Desenvolvendo
APIs usando
middlewares
Elton Minetto
@eminetto
http://eltonminetto.net
http://asemanago.com.br
elton@planrockr.com
Http Is The Foundation
Of The Web
Um cliente manda uma request
r.Method - HTTP method (GET, POST, PUT, PATCH, DELETE etc.)
r.URL.Path - Request path (/things/123)
r.URL.String() - Full URL
r.URL.Query() - Query parameters (q=something&p=2)
r.Body - io.ReadCloser of the request body
O servidor retorna uma response
type ResponseWriter interface {
Header() Header
Write([]byte) (int, error)
WriteHeader(int)
}
Middlewares
Between the request and response
Enrico Zimuel
HTTP middleware is not for your Domain work. The
middleware is a path in to, and out of, the core Domain.
Paul M. Jones
Run code before and after handler code
Mat Ryer
Desenvolvendo APIs em Go usando Middlewares
Exemplos
func middlewareOne(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("Executing before middlewareOne")
next.ServeHTTP(w, r)
log.Println("Executing after middlewareOne")
})
}
func middlewareTwo(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("Executing before middlewareTwo")
if r.URL.Path != "/" {
return
}
next.ServeHTTP(w, r)
log.Println("Executing after middlewareTwo")
})
}
func final(w http.ResponseWriter, r *http.Request) {
log.Println("Executing finalHandler")
w.Write([]byte("OK"))
}
func main() {
finalHandler := http.HandlerFunc(final)
http.Handle("/", middlewareOne(middlewareTwo(finalHandler)))
http.ListenAndServe(":8000", nil)
}
https://github.com/justinas/alice
func main() {
finalHandler := http.HandlerFunc(final)
chain := alice.New(middlewareOne, middlewareTwo).Then(finalHandler)
http.ListenAndServe(":8000", chain)
}
package main
import (
"github.com/justinas/alice"
"net/http"
"planrockr"
)
func getCurrentSubscription(w http.ResponseWriter, r *http.Request) { ...
}
func main() {
chain := alice.New(planrockr.Auth,
planrockr.GetUserByToken).
Then(http.HandlerFunc(getCurrentSubscription))
http.ListenAndServe(":8000", chain)
}
package main
import (
"github.com/justinas/alice"
"net/http"
"planrockr"
)
func processEvent(next http.Handler) http.Handler { ...
}
func main() {
chain := alice.New(processEvent,
planrockr.ValidateHookData).
Then(http.HandlerFunc(planrockr.Enqueue))
http.ListenAndServe(":8000", chain)
}
Links
https://gist.github.com/eminetto/
e3bab34426ac9a0b83a538a0e421bbc8
Contato
@eminetto
http://eltonminetto.net
http://asemanago.com.br
elton@planrockr.com

More Related Content

PDF
PSR-7, middlewares e o futuro dos frameworks
PDF
Codeigniter : Two Step View - Concept Implementation
PPTX
Php server variables
PPT
Cakephpstudy5 hacks
PDF
Symfony 2.0 on PHP 5.3
PDF
Extending the WordPress REST API - Josh Pollock
PPTX
21.search in laravel
PDF
PSR-7, middlewares e o futuro dos frameworks
Codeigniter : Two Step View - Concept Implementation
Php server variables
Cakephpstudy5 hacks
Symfony 2.0 on PHP 5.3
Extending the WordPress REST API - Josh Pollock
21.search in laravel

What's hot (20)

PDF
APPlause - DemoCamp Munich
PDF
Twib in Yokoahma.pm 2010/3/5
PDF
エロサイト管理者の憂鬱3 - Hokkaiodo.pm#4 -
PDF
Silex Cheat Sheet
PPTX
Zero to SOLID
PDF
Mojolicious
PDF
Mojolicious
DOCX
Sadi service
DOCX
Example code for the SADI BMI Calculator Web Service
PPTX
Алексей Плеханов: Новинки Laravel 5
PDF
Blog Hacks 2011
PDF
TDC2015 Porto Alegre - Automate everything with Phing !
PDF
Psr 7 symfony-day
PDF
Build REST API clients for AngularJS
PDF
4.2 PHP Function
PDF
Complex Sites with Silex
PDF
YAPC::Asia 2010 Twitter解析サービス
PDF
Building Modern and Secure PHP Applications – Codementor Office Hours with Be...
PDF
Getting Started-with-Laravel
PPT
Class 6 - PHP Web Programming
APPlause - DemoCamp Munich
Twib in Yokoahma.pm 2010/3/5
エロサイト管理者の憂鬱3 - Hokkaiodo.pm#4 -
Silex Cheat Sheet
Zero to SOLID
Mojolicious
Mojolicious
Sadi service
Example code for the SADI BMI Calculator Web Service
Алексей Плеханов: Новинки Laravel 5
Blog Hacks 2011
TDC2015 Porto Alegre - Automate everything with Phing !
Psr 7 symfony-day
Build REST API clients for AngularJS
4.2 PHP Function
Complex Sites with Silex
YAPC::Asia 2010 Twitter解析サービス
Building Modern and Secure PHP Applications – Codementor Office Hours with Be...
Getting Started-with-Laravel
Class 6 - PHP Web Programming
Ad

Viewers also liked (13)

PDF
Do monolito ao micro serviço
PDF
Metodologias ágeis interativas
PDF
Leveraging a distributed architecture to your advantage
PDF
E-commerce e o novo consumidor
PDF
Inovação e tecnologia
PDF
Code Squad
PDF
De Padawan a Jedi - Versão 2016
PDF
Ao infinito e além com PHP memcached e Gearman
PDF
DevOps e PHP
PDF
PHP like a super hero
PDF
PHP para Adultos: Clean Code e Object Calisthenics
PDF
You code sucks, let's fix it
PDF
Otimização MySQL
Do monolito ao micro serviço
Metodologias ágeis interativas
Leveraging a distributed architecture to your advantage
E-commerce e o novo consumidor
Inovação e tecnologia
Code Squad
De Padawan a Jedi - Versão 2016
Ao infinito e além com PHP memcached e Gearman
DevOps e PHP
PHP like a super hero
PHP para Adultos: Clean Code e Object Calisthenics
You code sucks, let's fix it
Otimização MySQL
Ad

Similar to Desenvolvendo APIs em Go usando Middlewares (20)

PPTX
Intro to Node
ODP
Angular 4 The new Http Client Module
PPTX
Net/http and the http.handler interface
PPTX
Net/http and the http.handler interface
PDF
PDF
May 2010 - RestEasy
PDF
Clojure and the Web
KEY
Java web programming
PDF
Sun RPC (Remote Procedure Call)
PDF
Customising Your Own Web Framework In Go
PDF
Web Server.pdf
PDF
Middleware.pdf
PDF
Ruby HTTP clients comparison
PPT
Web
PPT
Introduction to web and php mysql
ODP
RESTing with JAX-RS
PDF
Exploring Async PHP (SF Live Berlin 2019)
PPT
Java Servlets
PPTX
Job Managment Portlet
PPT
Intoduction to Play Framework
Intro to Node
Angular 4 The new Http Client Module
Net/http and the http.handler interface
Net/http and the http.handler interface
May 2010 - RestEasy
Clojure and the Web
Java web programming
Sun RPC (Remote Procedure Call)
Customising Your Own Web Framework In Go
Web Server.pdf
Middleware.pdf
Ruby HTTP clients comparison
Web
Introduction to web and php mysql
RESTing with JAX-RS
Exploring Async PHP (SF Live Berlin 2019)
Java Servlets
Job Managment Portlet
Intoduction to Play Framework

More from Elton Minetto (20)

PDF
Go e Microserviços - Nascidos um para o outro
PDF
Object Calisthenics em Go
PDF
Programar != desenvolver software (v2)
PDF
Gerenciando uma startup no Github Projects
PDF
Clean Architecture
PDF
Serverless em Go
PDF
JAMstack
PDF
Clean architecture em Go - v2
PDF
Programar != desenvolver software
PDF
Clean Architecture em PHP
PDF
Clean Architecture in Golang
PDF
A jornada do desenvolvedor
PDF
Product and Technology
PDF
Code:Nation Tech Stack
PDF
Modernizando projetos legados usando APIs
PDF
12 factor in the PHP world
PDF
Building APIs using Go
PDF
Start you
PDF
O case da Compufácil e AWS
PDF
Introdução a Go
Go e Microserviços - Nascidos um para o outro
Object Calisthenics em Go
Programar != desenvolver software (v2)
Gerenciando uma startup no Github Projects
Clean Architecture
Serverless em Go
JAMstack
Clean architecture em Go - v2
Programar != desenvolver software
Clean Architecture em PHP
Clean Architecture in Golang
A jornada do desenvolvedor
Product and Technology
Code:Nation Tech Stack
Modernizando projetos legados usando APIs
12 factor in the PHP world
Building APIs using Go
Start you
O case da Compufácil e AWS
Introdução a Go

Recently uploaded (20)

PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Encapsulation theory and applications.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
Cloud computing and distributed systems.
PDF
Machine learning based COVID-19 study performance prediction
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
Big Data Technologies - Introduction.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
Advanced methodologies resolving dimensionality complications for autism neur...
Digital-Transformation-Roadmap-for-Companies.pptx
Encapsulation theory and applications.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Cloud computing and distributed systems.
Machine learning based COVID-19 study performance prediction
Building Integrated photovoltaic BIPV_UPV.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
MIND Revenue Release Quarter 2 2025 Press Release
20250228 LYD VKU AI Blended-Learning.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Big Data Technologies - Introduction.pptx
Review of recent advances in non-invasive hemoglobin estimation
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation
Diabetes mellitus diagnosis method based random forest with bat algorithm
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Network Security Unit 5.pdf for BCA BBA.

Desenvolvendo APIs em Go usando Middlewares