GOing Forward

Fast Web Applications with Go Lang

GDG DevFest - Istanbul

Dec 6th, 2014

Ekin Eylem Ozekin

Outline

  • Introduction to Go
  • Go Basics
  • Web with Go
  • Make the web faster - Why Go?
  • Demos
  • Q & As

About Me

  • Background

    • BSc. in Computer Science, MSc. in Software Eng.

  • Experience

    • OS projects, freelance, banking, TA, Aviation...

  • Interests

    • Software, technology & web

Introduction to Go

  • Build around 2007, announced at 2009
  • By "GO"ogle, also known as Golang
  • Open Source

WHY A New Language?

Go LANG

Performance of Statically-typed languages

 

 

 

 

 

Usability of

Dynamic programming languages

 

 

 

 

+

Go BaSICS

  • Similar to C
  • Statically typed, compiled
  • No pointer arithmetic
  • Influenced by Erlang's concurrency: goroutines

Go BASICs

  • Automatic memory management, structs & interfaces, type inference
  • First class functions, suitable to functional programming
  • Concurrency support: goroutines & channels

GO BASICS

  • Ideal for fast, distributed systems
  • Can import libraries directly from URLs
  • Built-in UTF-8 support (İ, ç etc. works perfectly)
  • Extensive standard libs

Package management

  • Download a package:
    •  go get github.com/foo/bar

  • Remote import paths also work:
    • import "github.com/baz/qux"

Github, Bitbucket, Google Code & Launchpad are supported

COding with Go

package main

import (
  "fmt"
  "net/http"
)

func get_name() (string, string) {
  // No reason to break a few rules, right
  var hello = "Hello "
  audience := "DevFestTR"
  return hello, audience
}

func handler(writer http.ResponseWriter, request *http.Request) {
  hello, audience := get_name()
  fmt.Fprintf(writer, hello + audience)
}

func main() {
  http.HandleFunc("/", handler)
  http.ListenAndServe(":8080", nil)
}

More on this later...

Written as read left to right
No semicolons
 Multiple return value
(think of tuples in Python)
Single binary file after compile

WEb With GO

  • Built-in http package
  • Integrated AppEngine libraries
  • Similar to J2EE Servlets
  • More like a Micro-framework
  • Web development with the performance of C
  • Might be deployed with built-in server (port listener actually)
  • Deploy to Apache or Nginx with FastCGI
  • Also mod_go for Apache
  • Deploy to AppEngine or Heroku

 

WEB WITH GO

WHy Go?  - Feature highlights...

Concurrency

Runtime

 

Pass by Value

 

Native & Fast

Type Systems

GO

PROS

  • Micro-framework style http package
  • CGI support - kinda old but solid and useful
  • Compiled, fast performance
  • C like syntax but better
  • More standard libraries
  • API is mature enough

CONS

  • Not easier then PHP

        (or Ruby or Python)

  • Not as widely used as others
  • Not proven enough

        (yet can be argued)

Last Word...

  • Service Oriented Architecture & Micro Frameworks fit well
  • You don't have to use just Go, use with others...
  • Great general purpose language
    • Server software, web apps, statistical analyses, image processing, games etc.

 

New... Fun..

 

Google

Dropbox

SoundCloud

BBC

MongoDB

DEMO

A Web application with Go

SerVER SIDE

  • Bullet One
  • Bullet Two
  • Bullet Three
    1 package main
    2 import ("html/template"; "fmt"; "net/http"; "strconv")
    3 func main() {
    4   http.HandleFunc("/", form)
    5   http.HandleFunc("/show_age", form_handler)
    6   http.ListenAndServe(":8080", nil)
    7 }
    8 func form(writer http.ResponseWriter,
    9           request *http.Request) {
   10   genderList := []string { "Male", "Female" }
   11   t, _ := template.ParseFiles("form.html")
   12   t.Execute(writer, map[string]interface{} {
   13     "genders": genderList,
   14     "title": "DevFest Applicant Form",
   15   })
   16 }
   17 func form_handler(writer http.ResponseWriter,
   18                   request *http.Request) {
   19   gender := request.FormValue("gender")
   20   message := ""
   21   if ("1" == gender) {
   22     message = "You don't ask a woman her age."
   23   } else {
   24     age, _ := strconv.Atoi(request.FormValue("age"))
   25     if (age < 1000) {
   26       message = "This boy is still alive and kicking"
   27     } else {
   28       message = ”Still too young!"
   29     }  
   30   }
   31   fmt.Fprintf(writer, message)

Template COde

    1 <h1>{{.title}}</h1>
    2 <p>
    3   Fill in your gender and age.
    4   <br />
    5   And I will tell you if you are old or not...
    6 </p>
    7 <form action="/show_age" method="POST">
    8   <dl>
    9     <dt>Gender</dt>
   10     <dd>
   11       <select name="gender" style="width: 125px;">
   12         {{range $index, $value := .genders}}
   13           <option value="{{$index}}" />{{$value}}
   14         {{end}}
   15       </select>
   16     </dd>
   17     <dt>Age</dt>
   18     <dd><input type="text" name="age" /></dd>
   19   </dl>
   20   <input type="submit

Should I use Go

for My 

Project?

 Should I Learn GO?

 Then,

 WHY

HOW DO I DO WITH Go?

CODE EXAMPLES

How Do i parse json?

package main

import ("net/http"; "io/ioutil"; "encoding/json"; "strings"; "fmt")

func main() {
    response, _ := http.Get("http://ipinfo.io/json")
    defer response.Body.Close()
    body, _ := ioutil.ReadAll(response.Body)
    type IPInfo struct {
        Ip, Hostname, City, Region, Country, Loc, Org string
    }
    var ipInfo IPInfo
    dec := json.NewDecoder(strings.NewReader(string(body[:])))
    dec.Decode(&ipInfo)
    fmt.Printf("%s %s %s\n", ipInfo.Ip, ipInfo.City, ipInfo.Country)
}
String transformation
standard lib:encoding/json

How Do i Perform database queries?

package main

import("database/sql"; _ "github.com/go-sql-driver/mysql"; "log"; "fmt")

func main() {
    db, err := sql.Open("mysql", "root:lessecret@tcp(127.0.0.1:3306)/les_dernier_combat")
    if err != nil {
        log.Fatal(err)
    }   
    defer db.Close()
    var ( id int; name string; rank string ) 
    rows, err := db.Query("select id, name, rank from les_combatants where id < ?", 13) 
    if err != nil {
        log.Fatal(err)
    }   
    defer rows.Close()
    for rows.Next() {
        rows.Scan(&id, &name, &rank)
        fmt.Printf("%v: %v, %v\n", id, name, rank)
    }   
}
Defer pushes a function call onto list
Saved calls are executed after function returns

how do i serve json?

package main

import ("net/http"; "encoding/json")

func showHeroes(writer http.ResponseWriter, request *http.Request) {
    type SuperheroGroup struct {
        ID     int 
        GroupName   string
        Members []string
    }   
    group := SuperheroGroup{
        ID:     1,  
        GroupName:   "Fantastic Four",
        Members: []string{"Reed", "Sue", "Johnny", "Ben"},
    }   
    response, _ := json.Marshal(group)
    writer.Write(response)
}

func main() {
    http.HandleFunc("/heroes", showHeroes)
    http.ListenAndServe(":1234", nil)
}
request/response parameters
writing the response body

how do i go from zero to mvp?

func main() {
    m := martini.Classic()
    m.Get("/", func() string {
      return "mvp" // TODO: Have an actual MVP
    })
    m.Run()
}
$ gin
[gin] listening on port 3000
[martini] listening on :3001 (development)

Have some martini

Have some gin, too...

Hack away without interruptions...

Binding to the / endpoint
Restarts the application on code changes (Martini)

Is there a Database Abstraction layer?

As there are no classes ORM is a bit crippled. However, there are few implementations on that. You can find those here: 

http://jmoiron.net/blog/golang-orms/ 

There are also bindings for popular databases:

http://go-lang.cat-v.org/library-bindings

 

What can I use for User Interfaces?

There is a GTK binding for that. For more libraries you can check: http://go-lang.cat-v.org/library-bindings

FAQ

To return multiple values Python returns actually a Tuple data structure. Is it similar in Go , too?

No.

GO really returns multiple values :)

 

 

If I can something on a template, should I recompile in order to see changes?

No, you don't.

 If you make a change on the template code, all you have to do is refresh the page. 

However, you should be careful, when deploying to the server you should make sure that those templates exist too.

FAQ

Is there a web framework like Rails or Django for Go?

  • Not fully mature but good to go Revel:

http://revel.github.io/

  • Also, check out Gorilla:

http://www.gorillatoolkit.org/

  • Using MongoDB?

http://labix.org/mgo

 

 

Still have questions?

email: eeozekin@gmail.com

 

 

 

Ready to GO?

* Pun intended

Thanks for being HerE TODAY!

To Learn more about GO

GOing Forward: Web Programming with Go

By E. Eylem Ozekin

GOing Forward: Web Programming with Go

More on Go, programming & web.

  • 840