Upgrade to Pro — share decks privately, control downloads, hide ads and more …

From PHP to Go

Webconf Riga
November 14, 2015

From PHP to Go

More and more companies are using Go language in production environments. In this talk, I'll introduce you Go language comparing it with popular scripting language PHP, talk a little about working environment for Go developer, and discuss how Go can be adopted into company's existing technology stack.

Author: Dmitry Morozov
WebConf Riga 2015

Webconf Riga

November 14, 2015
Tweet

More Decks by Webconf Riga

Other Decks in Programming

Transcript

  1. Marketing slide Transact Pro is a leading online payment processing

    and card issuance non-banking institution in Baltic States with 12 year industry experience. Transact Pro provides online payment acceptance and processing turnkey solutions for more than 2500 e-commerce merchants worldwide. Services and solutions • Online processing services • Payment Gateway solution • Payment accounts • MasterCard payment cards • Online Bank and Mobile Bank • Consulting • Support
  2. Google preconditions • Ease of development • A lot of

    developers working with code base • Speed of compile • Good ecosystem • High performance • Efficient with modern computer environment • Static binaries
  3. Google approach • Designed by: Rob Pike, Robert Griesemer, Ken

    Thompson • Paradigm: compiled, concurrent, imperative, structured • C-family, with ideas from Java/Pascal/Modula/Limbo/… • As simple and plain as possible
  4. Web adopters • Concurrency out of the box • Awesome

    stdlib (HTTP stuff out of the box) • Execution and compilation speed • Simple language = faster development speed • Unit tests out of the box
  5. Transact Pro demands • Ideology (codestyle, types) • Great stdlib

    • Great documentation • Concurrency (goroutines and channels) • Execution speed • Easy to start
  6. First month with Go :) :( A lot of errors

    caught before runtime No vendoring management Maps and slices (go high-level arrays) No projects isolation No type casting magic No local community in Riga Routing and template engine out of the box Non-standard error handling - no exceptions Easy to install, no dependencies JSON, UTF-8 out of the box Builds without dependencies Awesome community not in Riga
  7. Hello, Go ! package main import ( "fmt" "net/http" )

    
 func main() { helloConst := func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "hi there !") } helloVariable := func(w http.ResponseWriter, r *http.Request) { title := r.URL.Path[len("/hello/"):] fmt.Fprintf(w, "hello, "+title) } 
 http.HandleFunc("/hello/", helloVariable) http.HandleFunc("/", helloConst) http.ListenAndServe(":8082", nil) }

  8. Return values func split(sum int) (x, y int) { x

    = sum * 4 / 9 y = sum - x return }
 func main() { fmt.Println(split(17)) }

  9. Concurrency runtime.GOMAXPROCS(2) var wg sync.WaitGroup wg.Add(2) fmt.Println("Starting Go Routines")
 go

    func() { defer wg.Done() for char := 'a'; char < 'a'+26; char++ { fmt.Printf("%c ", char) } }()
 go func() { defer wg.Done() for number := 1; number < 27; number++ { fmt.Printf("%d ", number) } }()
 fmt.Println("Waiting To Finish") wg.Wait() fmt.Println("\nTerminating Program")

  10. Concurrency Starting Go Routines Waiting To Finish a b 1

    2 3 4 c d e f 5 g h 6 i 7 j 8 k 9 10 11 12 l m n o p q 13 r s 14 t 15 u v 16 w 17 x y 18
  11. Concurrency is not parallelism • 1 routine = 2Kb of

    stack space • Cheap to create, destroy and switch • Channels, for high-level communications • Package sync for low-level sync
  12. Where are my classes ? "Bad programmers worry about the

    code. Good programmers worry about data structures and their relationships.” Linus Torvalds
  13. Where are my classes ? class Rectangle { public $w;

    public $h; public function __construct($w, $h){ $this->w = $w; $this->h = $h; } public function getArea(){ $this->logGetArea(); return $this->w*$this->h; } private function logGetArea(){ //do something } } $R = new Rectangle(10, 15); echo $R->getArea();
 package main import "fmt"
 type Rectangle struct{ w int h int }
 func (r Rectangle) GetArea() int{ logGetArea() return r.w*r.h }
 func logGetArea() { //do something } 
 func main() { r := Rectangle{w:10, h: 15} fmt.Println(r.GetArea()) }

  14. Web frameworks in Go func main() { router := gin.Default()

    router.GET("/user/:name", func(c *gin.Context) { name := c.Param("name") c.String(http.StatusOK, "Hello %s", name) }) router.GET("/user/:name/*action", func(c *gin.Context) { name := c.Param("name") action := c.Param("action") message := name + " is " + action c.String(http.StatusOK, message) }) router.Run(":8080") }

  15. ORM in Go type Model struct { ID uint `gorm:"primary_key"`

    CreatedAt time.Time UpdatedAt time.Time DeletedAt *time.Time }
 type User struct { gorm.Model Name string }
 db, err := gorm.Open("postgres", "user=gorm dbname=gorm sslmode=disable") // Update an existing struct db.First(&user) user.Name = “John” user.Age = 34 db.Save(&user)

  16. Custom logs in go import ( "os" log "github.com/Sirupsen/logrus" )


    func init() { // Log as JSON instead of the default ASCII formatter. log.SetFormatter(&log.JSONFormatter{}) // Output to stderr instead of stdout, could also be a file. log.SetOutput(os.Stderr) // Only log the warning severity or above. log.SetLevel(log.WarnLevel) }
 func main() { log.WithFields(log.Fields{ ."animal": "walrus", ."size": 10, }).Info("A group of walrus emerges from the ocean")

  17. How to start • Install Go properly • Setup your

    editor properly • Read “Effective Go” document • Do not skip steps into the manual • Profit !
  18. Language adoption • Fear: Google will drop Go support •

    Calmness: Community around the language
  19. Language adoption • Fear: It’s not production ready • Calmness:

    It’s used into production by many big and small companies: Docker, HashiCorp, iron.io, DropBox, BBC, SpaceX, Amazon, …
  20. Language adoption • Fear: We don’t need technology zoo •

    Calmness: Yes, you have to decide if you need Go into your technology stack
  21. TL;DR • created by Google for Google • fits for

    us, can fit for you • does it’s job really good • community around language • not a silver bullet • not a language X • haters gonna hate