Desenvolvendo APIs em Go usando Middlewares

Elton Minetto
Elton MinettoSoftware developer, teacher, speaker, open source evangelist, tech leader at Code:Nation
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
1 of 17

Recommended

PSR-7, middlewares e o futuro dos frameworks by
PSR-7, middlewares e o futuro dos frameworksPSR-7, middlewares e o futuro dos frameworks
PSR-7, middlewares e o futuro dos frameworksElton Minetto
3.4K views38 slides
Codeigniter : Two Step View - Concept Implementation by
Codeigniter : Two Step View - Concept ImplementationCodeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationAbdul Malik Ikhsan
4.2K views13 slides
Php server variables by
Php server variablesPhp server variables
Php server variablesJIGAR MAKHIJA
379 views5 slides
Cakephpstudy5 hacks by
Cakephpstudy5 hacksCakephpstudy5 hacks
Cakephpstudy5 hacksHiroki Shimizu
535 views31 slides
Symfony 2.0 on PHP 5.3 by
Symfony 2.0 on PHP 5.3Symfony 2.0 on PHP 5.3
Symfony 2.0 on PHP 5.3Fabien Potencier
3.5K views118 slides
Extending the WordPress REST API - Josh Pollock by
Extending the WordPress REST API - Josh PollockExtending the WordPress REST API - Josh Pollock
Extending the WordPress REST API - Josh PollockCaldera Labs
4.9K views30 slides

More Related Content

What's hot

APPlause - DemoCamp Munich by
APPlause - DemoCamp MunichAPPlause - DemoCamp Munich
APPlause - DemoCamp MunichPeter Friese
964 views24 slides
Twib in Yokoahma.pm 2010/3/5 by
Twib in Yokoahma.pm 2010/3/5Twib in Yokoahma.pm 2010/3/5
Twib in Yokoahma.pm 2010/3/5Yusuke Wada
1.7K views17 slides
エロサイト管理者の憂鬱3 - Hokkaiodo.pm#4 - by
エロサイト管理者の憂鬱3 - Hokkaiodo.pm#4 -エロサイト管理者の憂鬱3 - Hokkaiodo.pm#4 -
エロサイト管理者の憂鬱3 - Hokkaiodo.pm#4 -Yusuke Wada
3K views56 slides
Silex Cheat Sheet by
Silex Cheat SheetSilex Cheat Sheet
Silex Cheat SheetAndréia Bohner
4K views17 slides
Zero to SOLID by
Zero to SOLIDZero to SOLID
Zero to SOLIDVic Metcalfe
943 views84 slides
Mojolicious by
MojoliciousMojolicious
MojoliciousMarcos Rebelo
5.4K views44 slides

What's hot(20)

APPlause - DemoCamp Munich by Peter Friese
APPlause - DemoCamp MunichAPPlause - DemoCamp Munich
APPlause - DemoCamp Munich
Peter Friese964 views
Twib in Yokoahma.pm 2010/3/5 by Yusuke Wada
Twib in Yokoahma.pm 2010/3/5Twib in Yokoahma.pm 2010/3/5
Twib in Yokoahma.pm 2010/3/5
Yusuke Wada1.7K views
エロサイト管理者の憂鬱3 - Hokkaiodo.pm#4 - by Yusuke Wada
エロサイト管理者の憂鬱3 - Hokkaiodo.pm#4 -エロサイト管理者の憂鬱3 - Hokkaiodo.pm#4 -
エロサイト管理者の憂鬱3 - Hokkaiodo.pm#4 -
Yusuke Wada3K views
Example code for the SADI BMI Calculator Web Service by Mark Wilkinson
Example code for the SADI BMI Calculator Web ServiceExample code for the SADI BMI Calculator Web Service
Example code for the SADI BMI Calculator Web Service
Mark Wilkinson884 views
Алексей Плеханов: Новинки Laravel 5 by Oleg Poludnenko
Алексей Плеханов: Новинки Laravel 5Алексей Плеханов: Новинки Laravel 5
Алексей Плеханов: Новинки Laravel 5
Oleg Poludnenko1.5K views
Blog Hacks 2011 by Yusuke Wada
Blog Hacks 2011Blog Hacks 2011
Blog Hacks 2011
Yusuke Wada2.7K views
TDC2015 Porto Alegre - Automate everything with Phing ! by Matheus Marabesi
TDC2015 Porto Alegre - Automate everything with Phing !TDC2015 Porto Alegre - Automate everything with Phing !
TDC2015 Porto Alegre - Automate everything with Phing !
Matheus Marabesi1K views
Build REST API clients for AngularJS by Almog Baku
Build REST API clients for AngularJSBuild REST API clients for AngularJS
Build REST API clients for AngularJS
Almog Baku3.6K views
YAPC::Asia 2010 Twitter解析サービス by Yusuke Wada
YAPC::Asia 2010 Twitter解析サービスYAPC::Asia 2010 Twitter解析サービス
YAPC::Asia 2010 Twitter解析サービス
Yusuke Wada1.8K views
Building Modern and Secure PHP Applications – Codementor Office Hours with Be... by Arc & Codementor
Building Modern and Secure PHP Applications – Codementor Office Hours with Be...Building Modern and Secure PHP Applications – Codementor Office Hours with Be...
Building Modern and Secure PHP Applications – Codementor Office Hours with Be...
Arc & Codementor11.2K views
Class 6 - PHP Web Programming by Ahmed Swilam
Class 6 - PHP Web ProgrammingClass 6 - PHP Web Programming
Class 6 - PHP Web Programming
Ahmed Swilam1.8K views

Viewers also liked

Do monolito ao micro serviço by
Do monolito ao micro serviçoDo monolito ao micro serviço
Do monolito ao micro serviçoElton Minetto
848 views26 slides
Metodologias ágeis interativas by
Metodologias ágeis interativasMetodologias ágeis interativas
Metodologias ágeis interativasElton Minetto
1.6K views88 slides
Leveraging a distributed architecture to your advantage by
Leveraging a distributed architecture to your advantageLeveraging a distributed architecture to your advantage
Leveraging a distributed architecture to your advantageMichelangelo van Dam
1.5K views66 slides
E-commerce e o novo consumidor by
E-commerce e o novo consumidorE-commerce e o novo consumidor
E-commerce e o novo consumidorElton Minetto
684 views36 slides
Inovação e tecnologia by
Inovação  e tecnologiaInovação  e tecnologia
Inovação e tecnologiaElton Minetto
505 views35 slides
Code Squad by
Code SquadCode Squad
Code SquadElton Minetto
754 views12 slides

Viewers also liked(13)

Do monolito ao micro serviço by Elton Minetto
Do monolito ao micro serviçoDo monolito ao micro serviço
Do monolito ao micro serviço
Elton Minetto848 views
Metodologias ágeis interativas by Elton Minetto
Metodologias ágeis interativasMetodologias ágeis interativas
Metodologias ágeis interativas
Elton Minetto1.6K views
Leveraging a distributed architecture to your advantage by Michelangelo van Dam
Leveraging a distributed architecture to your advantageLeveraging a distributed architecture to your advantage
Leveraging a distributed architecture to your advantage
E-commerce e o novo consumidor by Elton Minetto
E-commerce e o novo consumidorE-commerce e o novo consumidor
E-commerce e o novo consumidor
Elton Minetto684 views
De Padawan a Jedi - Versão 2016 by Elton Minetto
De Padawan a Jedi - Versão 2016De Padawan a Jedi - Versão 2016
De Padawan a Jedi - Versão 2016
Elton Minetto627 views
Ao infinito e além com PHP memcached e Gearman by Elton Minetto
Ao infinito e além com PHP memcached e GearmanAo infinito e além com PHP memcached e Gearman
Ao infinito e além com PHP memcached e Gearman
Elton Minetto4K views
PHP para Adultos: Clean Code e Object Calisthenics by Guilherme Blanco
PHP para Adultos: Clean Code e Object CalisthenicsPHP para Adultos: Clean Code e Object Calisthenics
PHP para Adultos: Clean Code e Object Calisthenics
Guilherme Blanco17.2K views
You code sucks, let's fix it by Rafael Dohms
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
Rafael Dohms56.4K views

Similar to Desenvolvendo APIs em Go usando Middlewares

Intro to Node by
Intro to NodeIntro to Node
Intro to NodeAaron Stannard
5.2K views25 slides
Angular 4 The new Http Client Module by
Angular 4 The new Http Client ModuleAngular 4 The new Http Client Module
Angular 4 The new Http Client Modulearjun singh
1.2K views19 slides
Net/http and the http.handler interface by
Net/http and the http.handler interfaceNet/http and the http.handler interface
Net/http and the http.handler interfaceJoakim Gustin
75 views42 slides
Net/http and the http.handler interface by
Net/http and the http.handler interfaceNet/http and the http.handler interface
Net/http and the http.handler interfaceEvolve
266 views42 slides
RESTEasy by
RESTEasyRESTEasy
RESTEasyMassimiliano Dessì
1.7K views37 slides
May 2010 - RestEasy by
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasyJBug Italy
1.3K views37 slides

Similar to Desenvolvendo APIs em Go usando Middlewares(20)

Angular 4 The new Http Client Module by arjun singh
Angular 4 The new Http Client ModuleAngular 4 The new Http Client Module
Angular 4 The new Http Client Module
arjun singh1.2K views
Net/http and the http.handler interface by Joakim Gustin
Net/http and the http.handler interfaceNet/http and the http.handler interface
Net/http and the http.handler interface
Joakim Gustin75 views
Net/http and the http.handler interface by Evolve
Net/http and the http.handler interfaceNet/http and the http.handler interface
Net/http and the http.handler interface
Evolve266 views
May 2010 - RestEasy by JBug Italy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
JBug Italy1.3K views
Clojure and the Web by nickmbailey
Clojure and the WebClojure and the Web
Clojure and the Web
nickmbailey1.9K views
Sun RPC (Remote Procedure Call) by Peter R. Egli
Sun RPC (Remote Procedure Call)Sun RPC (Remote Procedure Call)
Sun RPC (Remote Procedure Call)
Peter R. Egli13.3K views
Customising Your Own Web Framework In Go by Jonathan Gomez
Customising Your Own Web Framework In GoCustomising Your Own Web Framework In Go
Customising Your Own Web Framework In Go
Jonathan Gomez1.3K views
Web by googli
WebWeb
Web
googli473 views
Introduction to web and php mysql by Programmer Blog
Introduction to web and php mysqlIntroduction to web and php mysql
Introduction to web and php mysql
Programmer Blog476 views
Exploring Async PHP (SF Live Berlin 2019) by dantleech
Exploring Async PHP (SF Live Berlin 2019)Exploring Async PHP (SF Live Berlin 2019)
Exploring Async PHP (SF Live Berlin 2019)
dantleech483 views
Job Managment Portlet by riround
Job Managment PortletJob Managment Portlet
Job Managment Portlet
riround610 views
Intoduction to Play Framework by Knoldus Inc.
Intoduction to Play FrameworkIntoduction to Play Framework
Intoduction to Play Framework
Knoldus Inc.2.2K views
T2 by Mo Ch
T2T2
T2
Mo Ch348 views

More from Elton Minetto

Go e Microserviços - Nascidos um para o outro by
Go e Microserviços - Nascidos um para o outroGo e Microserviços - Nascidos um para o outro
Go e Microserviços - Nascidos um para o outroElton Minetto
1.9K views37 slides
Object Calisthenics em Go by
Object Calisthenics em GoObject Calisthenics em Go
Object Calisthenics em GoElton Minetto
792 views79 slides
Programar != desenvolver software (v2) by
Programar != desenvolver software (v2)Programar != desenvolver software (v2)
Programar != desenvolver software (v2)Elton Minetto
341 views22 slides
Gerenciando uma startup no Github Projects by
Gerenciando uma startup no Github ProjectsGerenciando uma startup no Github Projects
Gerenciando uma startup no Github ProjectsElton Minetto
402 views30 slides
Clean Architecture by
Clean ArchitectureClean Architecture
Clean ArchitectureElton Minetto
912 views37 slides
Serverless em Go by
Serverless em GoServerless em Go
Serverless em GoElton Minetto
428 views31 slides

More from Elton Minetto(20)

Go e Microserviços - Nascidos um para o outro by Elton Minetto
Go e Microserviços - Nascidos um para o outroGo e Microserviços - Nascidos um para o outro
Go e Microserviços - Nascidos um para o outro
Elton Minetto1.9K views
Object Calisthenics em Go by Elton Minetto
Object Calisthenics em GoObject Calisthenics em Go
Object Calisthenics em Go
Elton Minetto792 views
Programar != desenvolver software (v2) by Elton Minetto
Programar != desenvolver software (v2)Programar != desenvolver software (v2)
Programar != desenvolver software (v2)
Elton Minetto341 views
Gerenciando uma startup no Github Projects by Elton Minetto
Gerenciando uma startup no Github ProjectsGerenciando uma startup no Github Projects
Gerenciando uma startup no Github Projects
Elton Minetto402 views
Clean architecture em Go - v2 by Elton Minetto
Clean architecture em Go - v2Clean architecture em Go - v2
Clean architecture em Go - v2
Elton Minetto652 views
Programar != desenvolver software by Elton Minetto
Programar != desenvolver softwareProgramar != desenvolver software
Programar != desenvolver software
Elton Minetto1.6K views
Clean Architecture em PHP by Elton Minetto
Clean Architecture em PHPClean Architecture em PHP
Clean Architecture em PHP
Elton Minetto3.3K views
Clean Architecture in Golang by Elton Minetto
Clean Architecture in GolangClean Architecture in Golang
Clean Architecture in Golang
Elton Minetto1.4K views
A jornada do desenvolvedor by Elton Minetto
A jornada do desenvolvedorA jornada do desenvolvedor
A jornada do desenvolvedor
Elton Minetto636 views
Modernizando projetos legados usando APIs by Elton Minetto
Modernizando projetos legados usando APIsModernizando projetos legados usando APIs
Modernizando projetos legados usando APIs
Elton Minetto1K views
12 factor in the PHP world by Elton Minetto
12 factor in the PHP world12 factor in the PHP world
12 factor in the PHP world
Elton Minetto1.4K views
O case da Compufácil e AWS by Elton Minetto
O case da Compufácil e AWSO case da Compufácil e AWS
O case da Compufácil e AWS
Elton Minetto256 views

Recently uploaded

Kyo - Functional Scala 2023.pdf by
Kyo - Functional Scala 2023.pdfKyo - Functional Scala 2023.pdf
Kyo - Functional Scala 2023.pdfFlavio W. Brasil
368 views92 slides
PRODUCT LISTING.pptx by
PRODUCT LISTING.pptxPRODUCT LISTING.pptx
PRODUCT LISTING.pptxangelicacueva6
14 views1 slide
Vertical User Stories by
Vertical User StoriesVertical User Stories
Vertical User StoriesMoisés Armani Ramírez
14 views16 slides
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院 by
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院IttrainingIttraining
52 views8 slides
20231123_Camunda Meetup Vienna.pdf by
20231123_Camunda Meetup Vienna.pdf20231123_Camunda Meetup Vienna.pdf
20231123_Camunda Meetup Vienna.pdfPhactum Softwareentwicklung GmbH
41 views73 slides
Case Study Copenhagen Energy and Business Central.pdf by
Case Study Copenhagen Energy and Business Central.pdfCase Study Copenhagen Energy and Business Central.pdf
Case Study Copenhagen Energy and Business Central.pdfAitana
16 views3 slides

Recently uploaded(20)

【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院 by IttrainingIttraining
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
Case Study Copenhagen Energy and Business Central.pdf by Aitana
Case Study Copenhagen Energy and Business Central.pdfCase Study Copenhagen Energy and Business Central.pdf
Case Study Copenhagen Energy and Business Central.pdf
Aitana16 views
Data Integrity for Banking and Financial Services by Precisely
Data Integrity for Banking and Financial ServicesData Integrity for Banking and Financial Services
Data Integrity for Banking and Financial Services
Precisely21 views
AMAZON PRODUCT RESEARCH.pdf by JerikkLaureta
AMAZON PRODUCT RESEARCH.pdfAMAZON PRODUCT RESEARCH.pdf
AMAZON PRODUCT RESEARCH.pdf
JerikkLaureta26 views
STPI OctaNE CoE Brochure.pdf by madhurjyapb
STPI OctaNE CoE Brochure.pdfSTPI OctaNE CoE Brochure.pdf
STPI OctaNE CoE Brochure.pdf
madhurjyapb14 views
Unit 1_Lecture 2_Physical Design of IoT.pdf by StephenTec
Unit 1_Lecture 2_Physical Design of IoT.pdfUnit 1_Lecture 2_Physical Design of IoT.pdf
Unit 1_Lecture 2_Physical Design of IoT.pdf
StephenTec12 views
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ... by Jasper Oosterveld
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...
HTTP headers that make your website go faster - devs.gent November 2023 by Thijs Feryn
HTTP headers that make your website go faster - devs.gent November 2023HTTP headers that make your website go faster - devs.gent November 2023
HTTP headers that make your website go faster - devs.gent November 2023
Thijs Feryn22 views
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N... by James Anderson
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
James Anderson85 views

Desenvolvendo APIs em Go usando Middlewares