SlideShare a Scribd company logo
1 of 70
Download to read offline
import golang;
struct Microservice
Giulio De Donato - Giorgio Cefaro
rate our talk!
https://joind.in/14104
Giorgio Cefaro
Freelance Software Engineer
@giorrrgio
Single Responsability Principle - The Lemmings metaphor
Giulio De Donato
CTO @ chupamobile
@liuggio
Once upon a time ... Monolith
One Company
One Application
One Deploy
One Server
One Database
The developer has a permanent contract with the monolith
is the guardian of all the tricks
BIG complex problem
vs
lots of small simple problems
Bounded context
small components
SOA vs ….
MICROSERVICES:
While there is no precise definition of this architectural style,
there are certain common characteristics around
organization around business capability,
automated deployment, intelligence in the
endpoints, and decentralized control of languages
and data.
-- martin fowler
How small is “micro”?
Not easy to say a number for micro ...
php
ruby
nodejs
golang
scala
golang
Different language foreach component?
What microservices has in common?
Immutable microservices
Communication via API tecn.Agnostic
GOLANG
Why we chose it
GOLANG
Go programs are statically compiled
Go compiler target multiple platforms
and architectures
Linux, Mac OS X, FreeBSD, NetBSD, OpenBSD, Plan 9, and Microsoft
Windows OS and i386, amd64, ARM and IBM POWER architectures
are currently supported
GOLANG - PLATFORMS AND ARCHITECTURES
NO EXTERNAL LIBRARIES
NO VIRTUAL MACHINES
JUST A STATIC EXECUTABLE
NO JIT-COMPILING
Concurrency is easy to implement
through GOROUTINES , each goroutine
having a SMALL FOOTPRINT of memory
and being MULTIPLEXED through OS
threads to avoid that blocking routines
can block other running goroutines
GOLANG - CONCURRENCY
Go supports modern web technologies
through a set of bundled packages,
ready to import.
archive, bufio, builtin, bytes, compress, container, crypto,
database, debug, encoding, errors, expvar, flag, fmt, go,
hash, html, image, index, io, log, math, mime, net, os, path,
reflect, regexp, runtime, sort, strconv, strings, suffixarray, sync,
syscall, testing, text, time, unicode, unsafe
GOLANG - PACKAGES
// hello_codemotion.go
package main
import "fmt"
func main() {
// Create a channel to synchronize goroutines
done := make(chan bool)
// Execute println in goroutine
go func() {
fmt.Println("Hello Codemotion")
// Tell the main function everything is done.
// This channel is visible inside this goroutine because
// it is executed in the same address space.
done <- true
}()
fmt.Println("Bye Codemotion")
<-done // Wait for the goroutine to finish. what if we
// remove it?
}
$ go build hello_codemotion.go
$ ./hello_codemotion
Bye Codemotion
Hello Codemotion
Even if we run the goroutine that will print
the “Hello” as first, its output will be echoed
once it is synchronized with main (the “<-
done” final line)
Network I/O is supported through the
net package, which comes with TCP/IP,
UDP, DNS, and Unix domain socket
components.
Low level support is provided, but you
will probably only need Dial, Accept and
Listen
GOLANG - COMMUNICATION
The net/http package provides http
client and server implementations.
Building a web server is quite easy!
GOLANG - COMMUNICATION
package main
import "net/http"
import "log"
import "fmt"
func main() {
http.HandleFunc("/hello", func(w http.ResponseWriter, r
*http.Request) {
fmt.Fprintln(w, "Hello, Codemotion!")
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
The encoding package provides
interfaces shared by other packages
that convert data to and from byte-level
and textual representations:
encoding/json
encoding/xml
encoding/gob
GOLANG - COMMUNICATION
type Message struct {
Name string
Body string
Time int64
}
m := Message{"Codemotion", "Hello", 1294706395881547000}
b, err := json.Marshal(m)
// b will be
// {"Name":"Alice","Body":"Hello","Time":1294706395881547000}
encoding/json package provides structures
to read and write JSON data
type Foo struct {
A, B int64
}
func main() {
conn, err := net.Dial("tcp", "localhost:8080")
if err != nil {
log.Fatal("Connection error", err)
}
encoder := gob.NewEncoder(conn)
foo := &Foo{1, 2}
encoder.Encode(foo)
conn.Close()
}
encoding/gob package provides native
golang RPC with binary transmission of
structures
INTERFACE
ALL THE THINGS
explicit is always better than implicit
My always True sentence
Expose behaviour
person.GoAhed() vs person.foot += 1meter
Interface all the things
● interfaces on types of the same package
● interfaces on different packages
● interfaces between layers eg.UserInterface vs
Domain
● interfaces between different application on the same
machine
interfaces between different application on the net
cat access.log | grep “porn” | wc -l
Unix Pipe revolution
HTTP WINS
HTTP is the protocol, everybody has to study its RFC
HTTP is not easy, Request/Response
WEB FRAMEWORKS
There’s no more web framework in Golang,
Martini example
Web Framework implicit net protocol
WEB FRAMEWORKS
HTTP FRAMEWORKS
We need explicit HTTP
‘97 java, ‘03 python, ‘07 ruby, ‘11 symfony
We are using explicit interface for Request/Response
GOLANG
HTTP INTERFACE
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
The interface needs a ServeHTTP method
but we use a function with no ServeHTTP interface
how?
type Handler interface {
ServeHTTP(http.ResponseWriter,*http.Request)
}
// handlerFunc
func(http.ResponseWriter,*http.Request)
handler := http.HandlerFunc(handlerFunc)
handler.ServeHTTP(w, r)
Interface
func
trick
Unit test on handlers
We can also unit test the handler
Huge handler
Please don’t do huge handler
monolith similarity
Compositions
Higher-order function
EXECUTE handlerFunc
//0 START
//1 START
//2 START
Controller
//2 END
//1 END
//0 END
middleware
● logger request logger with custom format support
● csrf Cross-site request forgery protection
● compress Gzip compression middleware
● basicAuth basic http authentication
● bodyParser extensible request body parser
● json application/json parser
● urlencoded application/x-www-form-urlencoded parser
● multipart multipart/form-data parser
● timeout request timeouts
● cookieParser cookie parser
● session session management support with bundled MemoryStore
● cookieSession cookie-based session support
● methodOverride faux HTTP method support
● responseTime calculates response-time and exposes via X-Response-Time
● staticCache memory cache layer for the static() middleware
● static streaming static file server supporting Range and more
● directory directory listing middleware
● vhost virtual host sub-domain mapping middleware
● favicon efficient favicon server (with default icon)
● limit limit the bytesize of request bodies
● query automatic querystring parser, populating req.query
● errorHandler flexible error handler
● …. many more
middleware
middleware
HTTP2
The future is already arrived —
it's just not very evenly
distributed
-- william gibson
Microservices need AUTOMATION
AUTOMATION
Build, Deploy, Scale
ARCHITECTURE - DOCKER
ARCHITECTURE - DOCKER
Docker is an open-source project that
automates the deployment of
applications inside software containers.
http://en.wikipedia.org/wiki/Docker_(software)
ARCHITECTURE - DOCKER
Docker allows independent "containers"
to run within a single Linux instance,
avoiding the overhead of starting virtual
machines.
http://en.wikipedia.org/wiki/Docker_(software)
# Dockerfile
# golang image where workspace (GOPATH) configured at /go.
FROM golang:1.4-onbuild
EXPOSE 3000
A container can be configured through a
Dockerfile
In this basic configuration, we specify that
our image is derived FROM the golang
image, available through the Docker Hub,
and that our container will EXPOSE port
3000
https://docs.docker.com/reference/builder/
$ sudo docker build -t codemotion_container .
The golang image is a great solution for go
microservices, it is configured to take care of
compiling our program and copy it inside the
container, ready to go with a single
command. Cross compiling is supported too!
https://registry.hub.docker.com/_/golang/
Microservices need AUTOMATION
Microservices need ORCHESTRATION
ARCHITECTURE - DOCKER ORCHESTRATION TOOLS
http://blog.docker.com/2015/02/orchestrating-docker-with-machine-swarm-and-compose/
◇ Provision Docker on any infrastructure, from
laptop to public cloud instance
◇ Compose an app using both proprietary
containers and Docker Hub Official Repos
◇ Manage all containers of an app as a single
group
◇ Cluster an application’s containers to optimize
resources and provide high-availability
ARCHITECTURE - DOCKER MACHINE
http://blog.docker.com/2015/02/announcing-docker-machine-beta/
◇ Provision Docker Engines across various
providers both local and remote, secured with
TLS, or not.
◇ Lightweight management of machines: Starting,
stopping, removing, etc.
◇ Run remote commands or log in to machines
via SSH
◇ Upgrade the Docker Engine when a new version
is released
$ docker-machine create -d virtualbox dev
[info] Downloading boot2docker...
[info] Creating SSH key...
[info] Creating VirtualBox VM…
[...]
$ docker run busybox echo hello world
hello world
With Machine docker hosts can be spawned
and controlled on different computers and
virtual machines from you local docker
client. Different clouds too!
Machine supports Amazon EC2, Microsoft Azure, Microsoft Hyper-V
DigitalOcean, Google Compute Engine, OpenStack, Rackspace, SoftLayer,
VirtualBox, VMware Fusion, VMware vCloud Air, VMware vSphere and
counting!
ARCHITECTURE - DOCKER SWARM
http://blog.docker.com/2015/02/scaling-docker-with-swarm/
◇ Native clustering for Docker
◇ Swarm is a standard Docker image
◇ Run one command to create a cluster.
◇ Run another command to start Swarm.
◇ On each host where the Docker Engine is
running, run a command to join said cluster.
$ docker run swarm create
5d9bc2f39ccc00500b36f23d90994f5f # <- cluster_id
# swarm master
$ docker-machine create -d virtualbox --swarm --swarm-master --
swarm-discovery token://5d9bc2f39ccc00500b36f23d90994f5f my-
swarm
# swarm nodes
$ docker-machine create -d virtualbox --swarm --swarm-discovery
token://5d9bc2f39ccc00500b36f23d90994f5f my-swarm-node1
$ docker-machine create -d virtualbox --swarm --swarm-discovery
token://5d9bc2f39ccc00500b36f23d90994f5f my-swarm-node3
$ docker run -d --name redis_1 -e ‘affinity:container!=redis_*’ redis
$ docker run -d --name redis_2 -e ‘affinity:container!=redis_*’ redis
Run two redis servers, but don’t run both on
the same machine:
Add a constraint on the type of storage, we
want a machine that has SSD storage:
$ docker run -d -e constraint:storage==ssd mysql
ARCHITECTURE - DOCKER COMPOSE
https://blog.docker.com/2015/02/announcing-docker-compose/
◇ Define your application’s components in a
single file
◇ Start, stop, and rebuild services
◇ View the status of running services
◇ Stream the log output of running services
◇ Run a one-off command on a service
# docker-compose.yml
cart:
build: ./cart
links:
- redis
ports:
- "5000:5000"
shipment:
build: ./shipment
links:
- mongo
ports:
- "5000:5000"
redis:
image: redis
mongo:
image: mongodb
Microservices need MONITORING
MONITORING - SOUNDCLOUD’S PROMETHEUS
http://5pi.de/2015/01/26/monitor-docker-containers-with-prometheus/
◇ Recently open-sourced by SoundCloud
◇ Written in GO with native client for in-
application monitoring
◇ Easy docker container monitoring
◇ Highly dimensional data model
◇ Flexible query language
◇ Powerful metrics types
◇ Alerting on any expression
◇ No fracking dependencies
$ docker run -p 9090:9090 prom/prometheus
CREDITS
http://en.wikipedia.org/wiki/List_of_largest_monoliths_in_the_world
https://www.flickr.com/photos/robwatling/3411172879
https://www.flickr.com/photos/dsevilla/139656712 FLOWER
https://www.flickr.com/photos/nickpiggott/5212359135 BRICKS
https://vimeo.com/105751281 PCFMA
http://www.youtube.com/watch?v=QY8mL6WARIE HTTP interface is a lie
http://martinfowler.com/articles/consumerDrivenContracts.html
http://www.infoq.com/news/2014/07/building-deploying-microservices
https://talks.golang.org/2014/readability.slide#27
http://www.morewords.com/contains/go/
http://martinfowler.com/articles/microservices.html (come non citarlo :))
https://blog.golang.org/docker (figata che docker ha il suo env golang)
https://speakerdeck.com/stilkov/microservices-talk-berlin
http://www.infoq.com/articles/microservices-practical-tips
http://nginx.com/blog/microservices-at-netflix-architectural-best-practices/
http://www.reddit.
com/r/golang/comments/252wjh/are_you_using_golang_for_webapi_development_what/
https://justinas.org/embrace-gos-http-tools/
https://news.ycombinator.com/item?id=6869710
https://crate.io/blog/deploying-crate-with-docker-machine-swarm/
THERE’S NO GOOD TALK WITH NO REFERENCES
JOIN GOLANGIT!
http://goo.gl/9am5vO
https://joind.in/14104
Questions? Answers?

More Related Content

What's hot

Fluentd and PHP
Fluentd and PHPFluentd and PHP
Fluentd and PHP
chobi e
 
Docker in production service discovery with consul - road to opscon 2015
Docker in production  service discovery with consul - road to opscon 2015Docker in production  service discovery with consul - road to opscon 2015
Docker in production service discovery with consul - road to opscon 2015
Giovanni Toraldo
 

What's hot (20)

Golang workshop
Golang workshopGolang workshop
Golang workshop
 
Rest, sockets em golang
Rest, sockets em golangRest, sockets em golang
Rest, sockets em golang
 
jbang: Unleash the power of Java for shell scripting
jbang: Unleash the power of Java for shell scriptingjbang: Unleash the power of Java for shell scripting
jbang: Unleash the power of Java for shell scripting
 
Dependency management in golang
Dependency management in golangDependency management in golang
Dependency management in golang
 
Fast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPCFast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPC
 
Build microservice with gRPC in golang
Build microservice with gRPC in golangBuild microservice with gRPC in golang
Build microservice with gRPC in golang
 
Docker and Fluentd
Docker and FluentdDocker and Fluentd
Docker and Fluentd
 
Pragmatic Monolith-First, easy to decompose, clean architecture
Pragmatic Monolith-First, easy to decompose, clean architecturePragmatic Monolith-First, easy to decompose, clean architecture
Pragmatic Monolith-First, easy to decompose, clean architecture
 
Golang from Scala developer’s perspective
Golang from Scala developer’s perspectiveGolang from Scala developer’s perspective
Golang from Scala developer’s perspective
 
Let's go HTTPS-only! - More Than Buying a Certificate
Let's go HTTPS-only! - More Than Buying a CertificateLet's go HTTPS-only! - More Than Buying a Certificate
Let's go HTTPS-only! - More Than Buying a Certificate
 
Node.js Web Apps @ ebay scale
Node.js Web Apps @ ebay scaleNode.js Web Apps @ ebay scale
Node.js Web Apps @ ebay scale
 
Online Meetup: Why should container system / platform builders care about con...
Online Meetup: Why should container system / platform builders care about con...Online Meetup: Why should container system / platform builders care about con...
Online Meetup: Why should container system / platform builders care about con...
 
sed.pdf
sed.pdfsed.pdf
sed.pdf
 
WebRTC - Brings Real-Time to the Web
WebRTC - Brings Real-Time to the WebWebRTC - Brings Real-Time to the Web
WebRTC - Brings Real-Time to the Web
 
Fluentd and PHP
Fluentd and PHPFluentd and PHP
Fluentd and PHP
 
drone continuous Integration
drone continuous Integrationdrone continuous Integration
drone continuous Integration
 
Docker in production service discovery with consul - road to opscon 2015
Docker in production  service discovery with consul - road to opscon 2015Docker in production  service discovery with consul - road to opscon 2015
Docker in production service discovery with consul - road to opscon 2015
 
Building kubectl plugins with Quarkus | DevNation Tech Talk
Building kubectl plugins with Quarkus | DevNation Tech TalkBuilding kubectl plugins with Quarkus | DevNation Tech Talk
Building kubectl plugins with Quarkus | DevNation Tech Talk
 
Cleaning Up the Dirt of the Nineties - How New Protocols are Modernizing the Web
Cleaning Up the Dirt of the Nineties - How New Protocols are Modernizing the WebCleaning Up the Dirt of the Nineties - How New Protocols are Modernizing the Web
Cleaning Up the Dirt of the Nineties - How New Protocols are Modernizing the Web
 
Setup docker on existing application
Setup docker on existing applicationSetup docker on existing application
Setup docker on existing application
 

Viewers also liked

Leaphly fight monolothic today
Leaphly fight monolothic todayLeaphly fight monolothic today
Leaphly fight monolothic today
Giulio De Donato
 

Viewers also liked (20)

A microservice architecture based on golang
A microservice architecture based on golangA microservice architecture based on golang
A microservice architecture based on golang
 
Golang server design pattern
Golang server design patternGolang server design pattern
Golang server design pattern
 
HTTP2 and gRPC
HTTP2 and gRPCHTTP2 and gRPC
HTTP2 and gRPC
 
Write microservice in golang
Write microservice in golangWrite microservice in golang
Write microservice in golang
 
Modern Web 2016: Using Golang to build a smart IM Bot
Modern Web 2016: Using Golang to build a smart IM Bot Modern Web 2016: Using Golang to build a smart IM Bot
Modern Web 2016: Using Golang to build a smart IM Bot
 
Robert Kubis - gRPC - boilerplate to high-performance scalable APIs - code.t...
 Robert Kubis - gRPC - boilerplate to high-performance scalable APIs - code.t... Robert Kubis - gRPC - boilerplate to high-performance scalable APIs - code.t...
Robert Kubis - gRPC - boilerplate to high-performance scalable APIs - code.t...
 
Think horizontally ood, ddd and bdd
Think horizontally ood, ddd and bddThink horizontally ood, ddd and bdd
Think horizontally ood, ddd and bdd
 
Leaphly fight monolothic today
Leaphly fight monolothic todayLeaphly fight monolothic today
Leaphly fight monolothic today
 
Caching and data analysis will move your Symfony2 application to the next level
Caching and data analysis will move your Symfony2 application to the next levelCaching and data analysis will move your Symfony2 application to the next level
Caching and data analysis will move your Symfony2 application to the next level
 
Benchmark Profile and Boost your Symfony application
Benchmark Profile and Boost your Symfony applicationBenchmark Profile and Boost your Symfony application
Benchmark Profile and Boost your Symfony application
 
Docker italia fatti un container tutto tuo
Docker italia fatti un container tutto tuoDocker italia fatti un container tutto tuo
Docker italia fatti un container tutto tuo
 
Google Go! language
Google Go! languageGoogle Go! language
Google Go! language
 
Go lang
Go langGo lang
Go lang
 
Architecting for the Cloud using NetflixOSS - Codemash Workshop
Architecting for the Cloud using NetflixOSS - Codemash WorkshopArchitecting for the Cloud using NetflixOSS - Codemash Workshop
Architecting for the Cloud using NetflixOSS - Codemash Workshop
 
Json web token api authorization
Json web token api authorizationJson web token api authorization
Json web token api authorization
 
Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?
 
用 Docker 改善團隊合作模式
用 Docker 改善團隊合作模式用 Docker 改善團隊合作模式
用 Docker 改善團隊合作模式
 
13 practical tips for writing secure golang applications
13 practical tips for writing secure golang applications13 practical tips for writing secure golang applications
13 practical tips for writing secure golang applications
 
Enabling Googley microservices with HTTP/2 and gRPC.
Enabling Googley microservices with HTTP/2 and gRPC.Enabling Googley microservices with HTTP/2 and gRPC.
Enabling Googley microservices with HTTP/2 and gRPC.
 
Bringing Learnings from Googley Microservices with gRPC - Varun Talwar, Google
Bringing Learnings from Googley Microservices with gRPC - Varun Talwar, GoogleBringing Learnings from Googley Microservices with gRPC - Varun Talwar, Google
Bringing Learnings from Googley Microservices with gRPC - Varun Talwar, Google
 

Similar to Import golang; struct microservice

Developing and Deploying PHP with Docker
Developing and Deploying PHP with DockerDeveloping and Deploying PHP with Docker
Developing and Deploying PHP with Docker
Patrick Mizer
 

Similar to Import golang; struct microservice (20)

nullcon 2010 - Intelligent debugging and in memory fuzzing
nullcon 2010 - Intelligent debugging and in memory fuzzingnullcon 2010 - Intelligent debugging and in memory fuzzing
nullcon 2010 - Intelligent debugging and in memory fuzzing
 
presentation @ docker meetup
presentation @ docker meetuppresentation @ docker meetup
presentation @ docker meetup
 
Docker - Der Wal in der Kiste
Docker - Der Wal in der KisteDocker - Der Wal in der Kiste
Docker - Der Wal in der Kiste
 
Nagios Conference 2014 - Spenser Reinhardt - Detecting Security Breaches With...
Nagios Conference 2014 - Spenser Reinhardt - Detecting Security Breaches With...Nagios Conference 2014 - Spenser Reinhardt - Detecting Security Breaches With...
Nagios Conference 2014 - Spenser Reinhardt - Detecting Security Breaches With...
 
Accelerate your development with Docker
Accelerate your development with DockerAccelerate your development with Docker
Accelerate your development with Docker
 
Accelerate your software development with Docker
Accelerate your software development with DockerAccelerate your software development with Docker
Accelerate your software development with Docker
 
Real-World Docker: 10 Things We've Learned
Real-World Docker: 10 Things We've Learned  Real-World Docker: 10 Things We've Learned
Real-World Docker: 10 Things We've Learned
 
JDD2014: Docker.io - versioned linux containers for JVM devops - Dominik Dorn
JDD2014: Docker.io - versioned linux containers for JVM devops - Dominik DornJDD2014: Docker.io - versioned linux containers for JVM devops - Dominik Dorn
JDD2014: Docker.io - versioned linux containers for JVM devops - Dominik Dorn
 
From development environments to production deployments with Docker, Compose,...
From development environments to production deployments with Docker, Compose,...From development environments to production deployments with Docker, Compose,...
From development environments to production deployments with Docker, Compose,...
 
Adventures in docker compose
Adventures in docker composeAdventures in docker compose
Adventures in docker compose
 
Docker 101
Docker 101 Docker 101
Docker 101
 
Better Operations into the Cloud
Better Operations  into the CloudBetter Operations  into the Cloud
Better Operations into the Cloud
 
Настройка окружения для кросскомпиляции проектов на основе docker'a
Настройка окружения для кросскомпиляции проектов на основе docker'aНастройка окружения для кросскомпиляции проектов на основе docker'a
Настройка окружения для кросскомпиляции проектов на основе docker'a
 
Docker 101 Checonf 2016
Docker 101 Checonf 2016Docker 101 Checonf 2016
Docker 101 Checonf 2016
 
Containers, Docker, and Microservices: the Terrific Trio
Containers, Docker, and Microservices: the Terrific TrioContainers, Docker, and Microservices: the Terrific Trio
Containers, Docker, and Microservices: the Terrific Trio
 
Docker Container As A Service - Mix-IT 2016
Docker Container As A Service - Mix-IT 2016Docker Container As A Service - Mix-IT 2016
Docker Container As A Service - Mix-IT 2016
 
Agile Brown Bag - Vagrant & Docker: Introduction
Agile Brown Bag - Vagrant & Docker: IntroductionAgile Brown Bag - Vagrant & Docker: Introduction
Agile Brown Bag - Vagrant & Docker: Introduction
 
Release with confidence
Release with confidenceRelease with confidence
Release with confidence
 
Developing and Deploying PHP with Docker
Developing and Deploying PHP with DockerDeveloping and Deploying PHP with Docker
Developing and Deploying PHP with Docker
 
Kubernetes for the PHP developer
Kubernetes for the PHP developerKubernetes for the PHP developer
Kubernetes for the PHP developer
 

More from Giulio De Donato

More from Giulio De Donato (7)

Lets isolate a process with no container like docker
Lets isolate a process with no container like dockerLets isolate a process with no container like docker
Lets isolate a process with no container like docker
 
More developers on DevOps with Docker orchestration
More developers on DevOps with Docker orchestrationMore developers on DevOps with Docker orchestration
More developers on DevOps with Docker orchestration
 
really really really awesome php application with bdd behat and iterfaces
really really really awesome php application with bdd behat and iterfacesreally really really awesome php application with bdd behat and iterfaces
really really really awesome php application with bdd behat and iterfaces
 
I came i saw i go - golang it meetup codemotion rome 2014
I came i saw i go - golang it meetup codemotion rome 2014I came i saw i go - golang it meetup codemotion rome 2014
I came i saw i go - golang it meetup codemotion rome 2014
 
It's all about behaviour, also in php - phpspec
It's all about behaviour, also in php - phpspecIt's all about behaviour, also in php - phpspec
It's all about behaviour, also in php - phpspec
 
Design pattern in Symfony2 - Nanos gigantium humeris insidentes
Design pattern in Symfony2 - Nanos gigantium humeris insidentesDesign pattern in Symfony2 - Nanos gigantium humeris insidentes
Design pattern in Symfony2 - Nanos gigantium humeris insidentes
 
Rationally boost your symfony2 application with caching tips and monitoring
Rationally boost your symfony2 application with caching tips and monitoringRationally boost your symfony2 application with caching tips and monitoring
Rationally boost your symfony2 application with caching tips and monitoring
 

Recently uploaded

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Recently uploaded (20)

%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 

Import golang; struct microservice

  • 1. import golang; struct Microservice Giulio De Donato - Giorgio Cefaro rate our talk! https://joind.in/14104
  • 2. Giorgio Cefaro Freelance Software Engineer @giorrrgio
  • 3. Single Responsability Principle - The Lemmings metaphor
  • 4. Giulio De Donato CTO @ chupamobile @liuggio
  • 5. Once upon a time ... Monolith One Company One Application One Deploy One Server One Database The developer has a permanent contract with the monolith is the guardian of all the tricks
  • 6. BIG complex problem vs lots of small simple problems Bounded context small components SOA vs ….
  • 7. MICROSERVICES: While there is no precise definition of this architectural style, there are certain common characteristics around organization around business capability, automated deployment, intelligence in the endpoints, and decentralized control of languages and data. -- martin fowler
  • 8. How small is “micro”? Not easy to say a number for micro ...
  • 9. php ruby nodejs golang scala golang Different language foreach component? What microservices has in common? Immutable microservices Communication via API tecn.Agnostic
  • 12. Go programs are statically compiled Go compiler target multiple platforms and architectures Linux, Mac OS X, FreeBSD, NetBSD, OpenBSD, Plan 9, and Microsoft Windows OS and i386, amd64, ARM and IBM POWER architectures are currently supported GOLANG - PLATFORMS AND ARCHITECTURES
  • 13. NO EXTERNAL LIBRARIES NO VIRTUAL MACHINES JUST A STATIC EXECUTABLE NO JIT-COMPILING
  • 14. Concurrency is easy to implement through GOROUTINES , each goroutine having a SMALL FOOTPRINT of memory and being MULTIPLEXED through OS threads to avoid that blocking routines can block other running goroutines GOLANG - CONCURRENCY
  • 15. Go supports modern web technologies through a set of bundled packages, ready to import. archive, bufio, builtin, bytes, compress, container, crypto, database, debug, encoding, errors, expvar, flag, fmt, go, hash, html, image, index, io, log, math, mime, net, os, path, reflect, regexp, runtime, sort, strconv, strings, suffixarray, sync, syscall, testing, text, time, unicode, unsafe GOLANG - PACKAGES
  • 16. // hello_codemotion.go package main import "fmt" func main() { // Create a channel to synchronize goroutines done := make(chan bool) // Execute println in goroutine go func() { fmt.Println("Hello Codemotion") // Tell the main function everything is done. // This channel is visible inside this goroutine because // it is executed in the same address space. done <- true }() fmt.Println("Bye Codemotion") <-done // Wait for the goroutine to finish. what if we // remove it? }
  • 17. $ go build hello_codemotion.go $ ./hello_codemotion Bye Codemotion Hello Codemotion Even if we run the goroutine that will print the “Hello” as first, its output will be echoed once it is synchronized with main (the “<- done” final line)
  • 18. Network I/O is supported through the net package, which comes with TCP/IP, UDP, DNS, and Unix domain socket components. Low level support is provided, but you will probably only need Dial, Accept and Listen GOLANG - COMMUNICATION
  • 19. The net/http package provides http client and server implementations. Building a web server is quite easy! GOLANG - COMMUNICATION
  • 20. package main import "net/http" import "log" import "fmt" func main() { http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, Codemotion!") }) log.Fatal(http.ListenAndServe(":8080", nil)) }
  • 21. The encoding package provides interfaces shared by other packages that convert data to and from byte-level and textual representations: encoding/json encoding/xml encoding/gob GOLANG - COMMUNICATION
  • 22. type Message struct { Name string Body string Time int64 } m := Message{"Codemotion", "Hello", 1294706395881547000} b, err := json.Marshal(m) // b will be // {"Name":"Alice","Body":"Hello","Time":1294706395881547000} encoding/json package provides structures to read and write JSON data
  • 23. type Foo struct { A, B int64 } func main() { conn, err := net.Dial("tcp", "localhost:8080") if err != nil { log.Fatal("Connection error", err) } encoder := gob.NewEncoder(conn) foo := &Foo{1, 2} encoder.Encode(foo) conn.Close() } encoding/gob package provides native golang RPC with binary transmission of structures
  • 25. explicit is always better than implicit My always True sentence
  • 26. Expose behaviour person.GoAhed() vs person.foot += 1meter
  • 27. Interface all the things ● interfaces on types of the same package ● interfaces on different packages ● interfaces between layers eg.UserInterface vs Domain ● interfaces between different application on the same machine interfaces between different application on the net
  • 28. cat access.log | grep “porn” | wc -l Unix Pipe revolution
  • 29.
  • 30. HTTP WINS HTTP is the protocol, everybody has to study its RFC HTTP is not easy, Request/Response
  • 31. WEB FRAMEWORKS There’s no more web framework in Golang, Martini example Web Framework implicit net protocol
  • 32. WEB FRAMEWORKS HTTP FRAMEWORKS We need explicit HTTP ‘97 java, ‘03 python, ‘07 ruby, ‘11 symfony
  • 33. We are using explicit interface for Request/Response
  • 34. GOLANG HTTP INTERFACE type Handler interface { ServeHTTP(ResponseWriter, *Request) } The interface needs a ServeHTTP method but we use a function with no ServeHTTP interface how?
  • 35. type Handler interface { ServeHTTP(http.ResponseWriter,*http.Request) } // handlerFunc func(http.ResponseWriter,*http.Request) handler := http.HandlerFunc(handlerFunc) handler.ServeHTTP(w, r) Interface func trick
  • 36. Unit test on handlers We can also unit test the handler
  • 37. Huge handler Please don’t do huge handler monolith similarity
  • 41.
  • 42. //0 START //1 START //2 START Controller //2 END //1 END //0 END middleware
  • 43. ● logger request logger with custom format support ● csrf Cross-site request forgery protection ● compress Gzip compression middleware ● basicAuth basic http authentication ● bodyParser extensible request body parser ● json application/json parser ● urlencoded application/x-www-form-urlencoded parser ● multipart multipart/form-data parser ● timeout request timeouts ● cookieParser cookie parser ● session session management support with bundled MemoryStore ● cookieSession cookie-based session support ● methodOverride faux HTTP method support ● responseTime calculates response-time and exposes via X-Response-Time ● staticCache memory cache layer for the static() middleware ● static streaming static file server supporting Range and more ● directory directory listing middleware ● vhost virtual host sub-domain mapping middleware ● favicon efficient favicon server (with default icon) ● limit limit the bytesize of request bodies ● query automatic querystring parser, populating req.query ● errorHandler flexible error handler ● …. many more middleware
  • 45. HTTP2 The future is already arrived — it's just not very evenly distributed -- william gibson
  • 49. ARCHITECTURE - DOCKER Docker is an open-source project that automates the deployment of applications inside software containers. http://en.wikipedia.org/wiki/Docker_(software)
  • 50. ARCHITECTURE - DOCKER Docker allows independent "containers" to run within a single Linux instance, avoiding the overhead of starting virtual machines. http://en.wikipedia.org/wiki/Docker_(software)
  • 51. # Dockerfile # golang image where workspace (GOPATH) configured at /go. FROM golang:1.4-onbuild EXPOSE 3000 A container can be configured through a Dockerfile In this basic configuration, we specify that our image is derived FROM the golang image, available through the Docker Hub, and that our container will EXPOSE port 3000 https://docs.docker.com/reference/builder/
  • 52. $ sudo docker build -t codemotion_container . The golang image is a great solution for go microservices, it is configured to take care of compiling our program and copy it inside the container, ready to go with a single command. Cross compiling is supported too! https://registry.hub.docker.com/_/golang/
  • 53.
  • 56. ARCHITECTURE - DOCKER ORCHESTRATION TOOLS http://blog.docker.com/2015/02/orchestrating-docker-with-machine-swarm-and-compose/ ◇ Provision Docker on any infrastructure, from laptop to public cloud instance ◇ Compose an app using both proprietary containers and Docker Hub Official Repos ◇ Manage all containers of an app as a single group ◇ Cluster an application’s containers to optimize resources and provide high-availability
  • 57. ARCHITECTURE - DOCKER MACHINE http://blog.docker.com/2015/02/announcing-docker-machine-beta/ ◇ Provision Docker Engines across various providers both local and remote, secured with TLS, or not. ◇ Lightweight management of machines: Starting, stopping, removing, etc. ◇ Run remote commands or log in to machines via SSH ◇ Upgrade the Docker Engine when a new version is released
  • 58. $ docker-machine create -d virtualbox dev [info] Downloading boot2docker... [info] Creating SSH key... [info] Creating VirtualBox VM… [...] $ docker run busybox echo hello world hello world With Machine docker hosts can be spawned and controlled on different computers and virtual machines from you local docker client. Different clouds too! Machine supports Amazon EC2, Microsoft Azure, Microsoft Hyper-V DigitalOcean, Google Compute Engine, OpenStack, Rackspace, SoftLayer, VirtualBox, VMware Fusion, VMware vCloud Air, VMware vSphere and counting!
  • 59. ARCHITECTURE - DOCKER SWARM http://blog.docker.com/2015/02/scaling-docker-with-swarm/ ◇ Native clustering for Docker ◇ Swarm is a standard Docker image ◇ Run one command to create a cluster. ◇ Run another command to start Swarm. ◇ On each host where the Docker Engine is running, run a command to join said cluster.
  • 60. $ docker run swarm create 5d9bc2f39ccc00500b36f23d90994f5f # <- cluster_id # swarm master $ docker-machine create -d virtualbox --swarm --swarm-master -- swarm-discovery token://5d9bc2f39ccc00500b36f23d90994f5f my- swarm # swarm nodes $ docker-machine create -d virtualbox --swarm --swarm-discovery token://5d9bc2f39ccc00500b36f23d90994f5f my-swarm-node1 $ docker-machine create -d virtualbox --swarm --swarm-discovery token://5d9bc2f39ccc00500b36f23d90994f5f my-swarm-node3
  • 61. $ docker run -d --name redis_1 -e ‘affinity:container!=redis_*’ redis $ docker run -d --name redis_2 -e ‘affinity:container!=redis_*’ redis Run two redis servers, but don’t run both on the same machine: Add a constraint on the type of storage, we want a machine that has SSD storage: $ docker run -d -e constraint:storage==ssd mysql
  • 62. ARCHITECTURE - DOCKER COMPOSE https://blog.docker.com/2015/02/announcing-docker-compose/ ◇ Define your application’s components in a single file ◇ Start, stop, and rebuild services ◇ View the status of running services ◇ Stream the log output of running services ◇ Run a one-off command on a service
  • 63. # docker-compose.yml cart: build: ./cart links: - redis ports: - "5000:5000" shipment: build: ./shipment links: - mongo ports: - "5000:5000" redis: image: redis mongo: image: mongodb
  • 65.
  • 66. MONITORING - SOUNDCLOUD’S PROMETHEUS http://5pi.de/2015/01/26/monitor-docker-containers-with-prometheus/ ◇ Recently open-sourced by SoundCloud ◇ Written in GO with native client for in- application monitoring ◇ Easy docker container monitoring ◇ Highly dimensional data model ◇ Flexible query language ◇ Powerful metrics types ◇ Alerting on any expression ◇ No fracking dependencies
  • 67. $ docker run -p 9090:9090 prom/prometheus
  • 68. CREDITS http://en.wikipedia.org/wiki/List_of_largest_monoliths_in_the_world https://www.flickr.com/photos/robwatling/3411172879 https://www.flickr.com/photos/dsevilla/139656712 FLOWER https://www.flickr.com/photos/nickpiggott/5212359135 BRICKS https://vimeo.com/105751281 PCFMA http://www.youtube.com/watch?v=QY8mL6WARIE HTTP interface is a lie http://martinfowler.com/articles/consumerDrivenContracts.html http://www.infoq.com/news/2014/07/building-deploying-microservices https://talks.golang.org/2014/readability.slide#27 http://www.morewords.com/contains/go/ http://martinfowler.com/articles/microservices.html (come non citarlo :)) https://blog.golang.org/docker (figata che docker ha il suo env golang) https://speakerdeck.com/stilkov/microservices-talk-berlin http://www.infoq.com/articles/microservices-practical-tips http://nginx.com/blog/microservices-at-netflix-architectural-best-practices/ http://www.reddit. com/r/golang/comments/252wjh/are_you_using_golang_for_webapi_development_what/ https://justinas.org/embrace-gos-http-tools/ https://news.ycombinator.com/item?id=6869710 https://crate.io/blog/deploying-crate-with-docker-machine-swarm/ THERE’S NO GOOD TALK WITH NO REFERENCES