Le langage
Go
http://golang.org/
Orléans Tech Talks - Stéphane Legrand - Février 2015
Licence de ce document
Cette présentation est sous licence Creative Commons : Attribution - Pas d’
Utilisation Commerciale - Partage dans les Mêmes Conditions 4.0 International.
Pour accéder à une copie de cette licence, merci de vous rendre à l'adresse
suivante http://creativecommons.org/licenses/by-nc-sa/4.0/ ou envoyez un
courrier à Creative Commons, 444 Castro Street, Suite 900, Mountain View,
California, 94041, USA.
Sommaire
● Historique
● Objectifs
● Hello world
● Quelques spécificités
● Exemple API REST
● Conclusion
Historique
● Projet interne Google à partir de 2007
● Open source depuis 2009
● Notamment Rob Pike et Ken Thompson
● Aujourd’hui, version 1.4
Objectifs
● Souplesse d’un langage interprété
● Efficacité et sécurité d’un langage compilé
● Moderne : réseau et multi-processeurs
● Rapide : compilation et exécution
● Portable : FreeBSD (v8 et sup.), Linux
(noyau 2.6.23 et sup.), Mac OS X (v10.6 et
sup.), Windows (XP et sup.)
Hello world
package main
import "fmt"
func main() {
fmt.Println("hello world")
}
% go run hello.go
hello world
% go build hello.go
% ./hello
hello world
Typage statique
package main
type t1 string
type t2 string
func f (v1 t1, v2 t2) (s string) {
s = v1 + v2
return
}
func main() {
f("v1", "v2")
}
% go build typage.go
./typage.go:5: invalid operation: v1 + v2 (mismatched types t1
and t2)
Structures
Collection de champs regroupés sous un type
package main
import "fmt"
type utilisateur struct {
identifiant string
groupe int
}
func main() {
fmt.Println(utilisateur{identifiant: "Toto", groupe: 42})
}
% go run structure.go
{Toto 42}
Méthodes
func (u utilisateur) incGroupeVal() { u.groupe++ }
func (u *utilisateur) incGroupePoint() { u.groupe++ }
func main() {
u := utilisateur{identifiant: "Toto", groupe: 42}
u.incGroupeVal()
fmt.Println(u)
u.incGroupePoint()
fmt.Println(u)
}
% go run methode.go
{Toto 42}
{Toto 43}
Interfaces / Définition
Interface = à la fois
un ensemble de méthodes
un type
type Animal interface {
Parle() string
}
Interfaces / OK
type Chien struct {}
func (c Chien) Parle() string { return "Wouf !" }
type Chat struct {}
func (c Chat) Parle() string { return "Miaou !" }
func main() {
animaux := []Animal{Chien{}, Chat{}}
for _, animal := range animaux { fmt.Println(animal.Parle()) }
}
% go build interface.go // COMPILATION OK
% ./interface
Wouf !
Miaou !
Interfaces / KO
type Chien struct {}
func (c Chien) Parle() string { return "Wouf !" }
type Chat struct {} // chat muet, pas de méthode Parle()
func main() {
animaux := []Animal{Chien{}, Chat{}}
for _, animal := range animaux { fmt.Println(animal.Parle()) }
}
% go build interface.go
./interface.go:16: cannot use Chat literal (type Chat) as type
Animal in array element:
Chat does not implement Animal (missing Parle method)
Programmation concurrente
package main
import ("fmt"; "time"; "math/rand")
func f (i int, msg string) {
rnd := rand.Intn(2000)
time.Sleep(time.Duration(rnd) * time.Millisecond)
fmt.Println(i, ": ", msg)
}
func main() {
for i := 0; i < 100000; i++ {
go f(i, "Go !")
}
var input string // attente appui d'une touche
fmt.Scanln(&input)
}
Outils intégrés / Tests
// fichier interface_test.go
package main
import "testing"
func TestChienParle(t *testing.T) {
chien := Chien{}
parole := chien.Parle()
if parole != "Wouf !" {
t.Error("S'attendait à Wouf, parole = ", parole)
}
}
% go test interface
ok interface 0.002s
Outils intégrés / Divers
● Comprend les gestionnaires de version
% go get github.com/julienschmidt/httprouter
● Indentation automatique du code
% go fmt …
● Générateur de documentation à partir des
commentaires
% godoc ...
Rapidité de compilation
Pas trouvé de benchmarks (désolé)...
Mais il suffit de l’essayer
pour le constater.
VRAIMENT, VRAIMENT RAPIDE !
Rapidité d’exécution / 1
http://www.techempower.com/benchmarks/#section=data-r9&hw=peak&test=json&l=dfk
http://benchmarksgame.alioth.debian.org/u64q/compare.php?lang=go&lang2=php
Rapidité d’exécution / 2
http://www.techempower.com/benchmarks/#section=data-r9&hw=peak&test=fortune&l=dfk
Richesse librairie standard
● (dé)compression : gzip, bzip2, zlib…
● (dé)chiffrement : aes, des, hmac, md5, rsa,
sha512…
● bases de données SQL (drivers tiers).
● encodage : base64, csv, json, xml…
● serveur HTTP
● expressions régulières
● opérations sur dates et heures
● Unicode
● ...
Bizarreries...
● Pas d’exceptions (mais v,err := f())
● Pas de type générique
● Erreur de pointeur nul possible
● Pas de librairie dynamique
● Pas d’héritage
http://tmikov.blogspot.fr/2015/02/you-dont-like-googles-go-because-you.html
Exemple REST / Architecture
NetNavigateur Apache
(proxy)
Serveur
Go
(HTTP)
SGBD
Exemple REST / Objectif
Si le serveur reçoit une requête GET
/nom/toto
Doit renvoyer une chaîne JSON
{"Nom":"toto"}
Exemple REST / Code - partie 1
package main
import (
// installation : go get github.com/julienschmidt/httprouter
"github.com/julienschmidt/httprouter"
"encoding/json"
"log"
"net/http"
)
type utilisateur struct {
Nom string // exporté pour JSON
}
Exemple REST / Code - partie 2
func main() {
router := httprouter.New()
router.GET("/nom/:nom", nom)
log.Fatal(http.ListenAndServe("localhost:8080", router))
}
Exemple REST / Code - partie 3
func nom(w http.ResponseWriter, r *http.Request, ps httprouter.Params)
{
u := utilisateur{}
u.Nom = ps.ByName("nom")
j, err := json.Marshal(u)
if err == nil {
w.Header().Set("Content-Type", "application/json")
w.Write(j)
} else {
log.Fatal(err)
}
}
Exemple REST / Exécution
% go build rest.go
% ./rest
% curl 'http://localhost:8080/nom/toto'
{"Nom":"toto"}
% curl 'http://localhost:8080/nom/titi'
{"Nom":"titi"}
Exemple REST / Benchmark
% siege -q -b -t 60S 'http://localhost:8080/nom/toto'
Transactions: 449160 hits
Availability: 100.00 %
Elapsed time: 59.09 secs
Data transferred: 6.00 MB
Response time: 0.00 secs
Transaction rate: 7601.81 trans/sec
Throughput: 0.10 MB/sec
Concurrency: 14.81
Successful transactions:449160
Failed transactions: 0
Longest transaction: 0.02
Shortest transaction: 0.00
Conclusion
● Pragmatique !
● Beaucoup de potentiel
● Utiliser “golang” pour recherches sur internet
Merci
Merci de votre attention
Questions ?

Contenu connexe

PDF
Pratique de la programmation en go
PDF
Communications Réseaux et HTTP avec PHP
PDF
PHPTour 2011 - PHP5.4
ODP
ZendFramework2 - Présentation
PDF
Presentation du Livre Django Avancé
PDF
Gestion de formulaires en PHP
PDF
PHP5 et les fichiers
PDF
Etes vous-pret pour php8 ?
Pratique de la programmation en go
Communications Réseaux et HTTP avec PHP
PHPTour 2011 - PHP5.4
ZendFramework2 - Présentation
Presentation du Livre Django Avancé
Gestion de formulaires en PHP
PHP5 et les fichiers
Etes vous-pret pour php8 ?

Tendances (20)

PDF
PPTX
Formation python 3
PPTX
Requêtes HTTP synchrones et asynchrones
PDF
Le client FTP de PHP5
PDF
Le client HTTP PHP5
PDF
Linux Administrateur
PDF
Fichier XML et PHP5
PDF
Client base de données en PHP5
PDF
Email et PHP5
PPTX
Introduction à Symfony
PDF
Configuration PHP5
PDF
Application web php5 html5 css3 bootstrap
PDF
PHP 7 et Symfony 3
PPT
Introduction à JavaScript
PDF
Présentation de PHP
ODP
Formation Linux lpi 101
PPTX
Python après 15 ans de JAVA
PPT
Introduction au langage PHP (1ere partie) élaborée par Marouan OMEZZINE
PPTX
Symfony2 - Un Framework PHP 5 Performant
PPT
PHP 5.3, PHP Next
Formation python 3
Requêtes HTTP synchrones et asynchrones
Le client FTP de PHP5
Le client HTTP PHP5
Linux Administrateur
Fichier XML et PHP5
Client base de données en PHP5
Email et PHP5
Introduction à Symfony
Configuration PHP5
Application web php5 html5 css3 bootstrap
PHP 7 et Symfony 3
Introduction à JavaScript
Présentation de PHP
Formation Linux lpi 101
Python après 15 ans de JAVA
Introduction au langage PHP (1ere partie) élaborée par Marouan OMEZZINE
Symfony2 - Un Framework PHP 5 Performant
PHP 5.3, PHP Next
Publicité

En vedette (20)

DOCX
Commande linux
PDF
Integration continue et déploiement automatisé
DOCX
Les 10 commandes utiles pour surveiller un système Linux
PPT
Concept de l’Intégration Continue
PPT
Stack Technologique Google
PDF
DevOps avec Ansible et Docker
DOCX
Analyse raj
PPTX
projet is
PPSX
Souper de filles ... avec moi!!!
PDF
Rapport de-christophe_sirugue_depute_de_saone-et-loire-1
PDF
Les gourous de l'égalitarisme, pères du chômage ?
PDF
Designspage 07072012
PDF
Rapport de synthese-_t._mandon
PPT
Rencontres SIG La Lettre 2013
PPS
Art de Vivre Lausanne- février & mars 2011
PDF
Crash du Rio-Paris: le rapport du BEA du 29 juillet 2011
PPTX
Groupe 106, lasnier le quang yan, la science et moi
PPTX
L'application Meilleurtaux sur Android
PPT
Chevauchée sarde + veronica murgia
Commande linux
Integration continue et déploiement automatisé
Les 10 commandes utiles pour surveiller un système Linux
Concept de l’Intégration Continue
Stack Technologique Google
DevOps avec Ansible et Docker
Analyse raj
projet is
Souper de filles ... avec moi!!!
Rapport de-christophe_sirugue_depute_de_saone-et-loire-1
Les gourous de l'égalitarisme, pères du chômage ?
Designspage 07072012
Rapport de synthese-_t._mandon
Rencontres SIG La Lettre 2013
Art de Vivre Lausanne- février & mars 2011
Crash du Rio-Paris: le rapport du BEA du 29 juillet 2011
Groupe 106, lasnier le quang yan, la science et moi
L'application Meilleurtaux sur Android
Chevauchée sarde + veronica murgia
Publicité

Similaire à Presentation langage go_19022015 (20)

PDF
Introduction au langage Go
PPT
Présentation Groovy
PPT
Présentation Groovy
PDF
Rich Desktop Applications
PDF
Dart JUG 2013
PPT
Annexe1 éTude Comparative Sur Les Moteurs De Recherche
PDF
Des tests modernes pour Drupal
PDF
Atoum, le framework de tests unitaires pour PHP 5.3 simple, moderne et intuit...
PDF
BBL - TDD pour les DevOps - Puppet
PPTX
ALT.Net Juin 2012 - Specflow
ODP
Déploiement PHP : de l'âge de pierre à nos jours.
PPT
Node, Grunt et leurs copains qui font de l’accessibilité tout seuls !
PPTX
PHP5: Endgame
PDF
Conférence #nwx2014 - Maxime Mauchaussée - Partager du code maintenable et év...
PDF
Php seance1
PDF
Détecter et nettoyer le contenu générique
PPT
2008-09-30 Administration automatisée avec Powershell
PDF
Big Data Viz (and much more!) with Apache Zeppelin
PDF
Mieux Développer en PHP avec Symfony
Introduction au langage Go
Présentation Groovy
Présentation Groovy
Rich Desktop Applications
Dart JUG 2013
Annexe1 éTude Comparative Sur Les Moteurs De Recherche
Des tests modernes pour Drupal
Atoum, le framework de tests unitaires pour PHP 5.3 simple, moderne et intuit...
BBL - TDD pour les DevOps - Puppet
ALT.Net Juin 2012 - Specflow
Déploiement PHP : de l'âge de pierre à nos jours.
Node, Grunt et leurs copains qui font de l’accessibilité tout seuls !
PHP5: Endgame
Conférence #nwx2014 - Maxime Mauchaussée - Partager du code maintenable et év...
Php seance1
Détecter et nettoyer le contenu générique
2008-09-30 Administration automatisée avec Powershell
Big Data Viz (and much more!) with Apache Zeppelin
Mieux Développer en PHP avec Symfony

Plus de Stéphane Legrand (7)

PDF
La programmation fonctionnelle avec le langage OCaml
PDF
L’environnement de programmation fonctionnelle DrRacket
PDF
Les modèles économiques du logiciel libre
PDF
Linux et les systèmes embarqués
PDF
Résolution de problèmes de classification par algorithmes évolutionnaires grâ...
PDF
ZFS et BTRFS
PDF
Les algorithmes évolutionnistes
La programmation fonctionnelle avec le langage OCaml
L’environnement de programmation fonctionnelle DrRacket
Les modèles économiques du logiciel libre
Linux et les systèmes embarqués
Résolution de problèmes de classification par algorithmes évolutionnaires grâ...
ZFS et BTRFS
Les algorithmes évolutionnistes

Presentation langage go_19022015

  • 1. Le langage Go http://golang.org/ Orléans Tech Talks - Stéphane Legrand - Février 2015
  • 2. Licence de ce document Cette présentation est sous licence Creative Commons : Attribution - Pas d’ Utilisation Commerciale - Partage dans les Mêmes Conditions 4.0 International. Pour accéder à une copie de cette licence, merci de vous rendre à l'adresse suivante http://creativecommons.org/licenses/by-nc-sa/4.0/ ou envoyez un courrier à Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.
  • 3. Sommaire ● Historique ● Objectifs ● Hello world ● Quelques spécificités ● Exemple API REST ● Conclusion
  • 4. Historique ● Projet interne Google à partir de 2007 ● Open source depuis 2009 ● Notamment Rob Pike et Ken Thompson ● Aujourd’hui, version 1.4
  • 5. Objectifs ● Souplesse d’un langage interprété ● Efficacité et sécurité d’un langage compilé ● Moderne : réseau et multi-processeurs ● Rapide : compilation et exécution ● Portable : FreeBSD (v8 et sup.), Linux (noyau 2.6.23 et sup.), Mac OS X (v10.6 et sup.), Windows (XP et sup.)
  • 6. Hello world package main import "fmt" func main() { fmt.Println("hello world") } % go run hello.go hello world % go build hello.go % ./hello hello world
  • 7. Typage statique package main type t1 string type t2 string func f (v1 t1, v2 t2) (s string) { s = v1 + v2 return } func main() { f("v1", "v2") } % go build typage.go ./typage.go:5: invalid operation: v1 + v2 (mismatched types t1 and t2)
  • 8. Structures Collection de champs regroupés sous un type package main import "fmt" type utilisateur struct { identifiant string groupe int } func main() { fmt.Println(utilisateur{identifiant: "Toto", groupe: 42}) } % go run structure.go {Toto 42}
  • 9. Méthodes func (u utilisateur) incGroupeVal() { u.groupe++ } func (u *utilisateur) incGroupePoint() { u.groupe++ } func main() { u := utilisateur{identifiant: "Toto", groupe: 42} u.incGroupeVal() fmt.Println(u) u.incGroupePoint() fmt.Println(u) } % go run methode.go {Toto 42} {Toto 43}
  • 10. Interfaces / Définition Interface = à la fois un ensemble de méthodes un type type Animal interface { Parle() string }
  • 11. Interfaces / OK type Chien struct {} func (c Chien) Parle() string { return "Wouf !" } type Chat struct {} func (c Chat) Parle() string { return "Miaou !" } func main() { animaux := []Animal{Chien{}, Chat{}} for _, animal := range animaux { fmt.Println(animal.Parle()) } } % go build interface.go // COMPILATION OK % ./interface Wouf ! Miaou !
  • 12. Interfaces / KO type Chien struct {} func (c Chien) Parle() string { return "Wouf !" } type Chat struct {} // chat muet, pas de méthode Parle() func main() { animaux := []Animal{Chien{}, Chat{}} for _, animal := range animaux { fmt.Println(animal.Parle()) } } % go build interface.go ./interface.go:16: cannot use Chat literal (type Chat) as type Animal in array element: Chat does not implement Animal (missing Parle method)
  • 13. Programmation concurrente package main import ("fmt"; "time"; "math/rand") func f (i int, msg string) { rnd := rand.Intn(2000) time.Sleep(time.Duration(rnd) * time.Millisecond) fmt.Println(i, ": ", msg) } func main() { for i := 0; i < 100000; i++ { go f(i, "Go !") } var input string // attente appui d'une touche fmt.Scanln(&input) }
  • 14. Outils intégrés / Tests // fichier interface_test.go package main import "testing" func TestChienParle(t *testing.T) { chien := Chien{} parole := chien.Parle() if parole != "Wouf !" { t.Error("S'attendait à Wouf, parole = ", parole) } } % go test interface ok interface 0.002s
  • 15. Outils intégrés / Divers ● Comprend les gestionnaires de version % go get github.com/julienschmidt/httprouter ● Indentation automatique du code % go fmt … ● Générateur de documentation à partir des commentaires % godoc ...
  • 16. Rapidité de compilation Pas trouvé de benchmarks (désolé)... Mais il suffit de l’essayer pour le constater. VRAIMENT, VRAIMENT RAPIDE !
  • 17. Rapidité d’exécution / 1 http://www.techempower.com/benchmarks/#section=data-r9&hw=peak&test=json&l=dfk http://benchmarksgame.alioth.debian.org/u64q/compare.php?lang=go&lang2=php
  • 18. Rapidité d’exécution / 2 http://www.techempower.com/benchmarks/#section=data-r9&hw=peak&test=fortune&l=dfk
  • 19. Richesse librairie standard ● (dé)compression : gzip, bzip2, zlib… ● (dé)chiffrement : aes, des, hmac, md5, rsa, sha512… ● bases de données SQL (drivers tiers). ● encodage : base64, csv, json, xml… ● serveur HTTP ● expressions régulières ● opérations sur dates et heures ● Unicode ● ...
  • 20. Bizarreries... ● Pas d’exceptions (mais v,err := f()) ● Pas de type générique ● Erreur de pointeur nul possible ● Pas de librairie dynamique ● Pas d’héritage http://tmikov.blogspot.fr/2015/02/you-dont-like-googles-go-because-you.html
  • 21. Exemple REST / Architecture NetNavigateur Apache (proxy) Serveur Go (HTTP) SGBD
  • 22. Exemple REST / Objectif Si le serveur reçoit une requête GET /nom/toto Doit renvoyer une chaîne JSON {"Nom":"toto"}
  • 23. Exemple REST / Code - partie 1 package main import ( // installation : go get github.com/julienschmidt/httprouter "github.com/julienschmidt/httprouter" "encoding/json" "log" "net/http" ) type utilisateur struct { Nom string // exporté pour JSON }
  • 24. Exemple REST / Code - partie 2 func main() { router := httprouter.New() router.GET("/nom/:nom", nom) log.Fatal(http.ListenAndServe("localhost:8080", router)) }
  • 25. Exemple REST / Code - partie 3 func nom(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { u := utilisateur{} u.Nom = ps.ByName("nom") j, err := json.Marshal(u) if err == nil { w.Header().Set("Content-Type", "application/json") w.Write(j) } else { log.Fatal(err) } }
  • 26. Exemple REST / Exécution % go build rest.go % ./rest % curl 'http://localhost:8080/nom/toto' {"Nom":"toto"} % curl 'http://localhost:8080/nom/titi' {"Nom":"titi"}
  • 27. Exemple REST / Benchmark % siege -q -b -t 60S 'http://localhost:8080/nom/toto' Transactions: 449160 hits Availability: 100.00 % Elapsed time: 59.09 secs Data transferred: 6.00 MB Response time: 0.00 secs Transaction rate: 7601.81 trans/sec Throughput: 0.10 MB/sec Concurrency: 14.81 Successful transactions:449160 Failed transactions: 0 Longest transaction: 0.02 Shortest transaction: 0.00
  • 28. Conclusion ● Pragmatique ! ● Beaucoup de potentiel ● Utiliser “golang” pour recherches sur internet
  • 29. Merci Merci de votre attention Questions ?