29
How I built my first web app in Go 16 Sep 2014 Audrey Lim [email protected] Twitter: @AudreyLim77

Golang slidesaudrey

Embed Size (px)

Citation preview

How I built my first web app in Go

16 Sep 2014

Audrey [email protected]

Twitter: @AudreyLim77

About Me

Building Go applications

About Me

Lawyer (1-2 yrs)

About Me

Lawyer (1-2 yrs)

Learning Journey May – Jul 2014: HTML, CSS, JS

About Me

Lawyer (1-2 yrs)

Learning Journey May – Jul 2014: HTML, CSS, JS

(codeacademy, books, websites)

About Me

Lawyer (1-2 yrs)

Learning Journey May – Jul 2014: HTML, CSS, JS mid-Jul 2014: Go (1st backend)

(codeacademy, books, websites)

About Me

Lawyer (1-2 yrs)

Learning Journey May – Jul 2014: HTML, CSS, JS mid-Jul 2014: Go (1st backend)

(codeacademy, books, websites)

(everywhere)

About Me

Lawyer (1-2 yrs)

Learning Journey May – Jul 2014: HTML, CSS, JS mid-Jul 2014: Go (1st backend) mid-Aug 2014: deployed 1st app – CRUD app

(codeacademy, books, websites)

(everywhere)

About Me

Lawyer (1-2 yrs)

Learning Journey May – Jul 2014: HTML, CSS, JS mid-Jul 2014: Go (1st backend)mid-Aug 2014: deployed 1st app – CRUD app end-Aug 2014: deployed 2nd app – API client

(codeacademy, books, websites)

(everywhere)

Go Resources

golang.org

Books and websites

Sample applications

Stackoverflow, Go-nuts mailing list

Go Resources

golang.org (Go Tour, Docs, Go blog)

Books and websites

Sample applications

Stackoverflow, Go-nuts mailing list

Go Resources

golang.org (Go Tour, Docs, Go blog)

Books and websites (www.golang-book.com, www.gobyexample.com)

Sample applications

Stackoverflow, Go-nuts mailing list

Go Resources

golang.org (Go Tour, Docs, Go blog)

Books and websites (www.golang-book.com, www.gobyexample.com)

Sample applications (Go Wiki, from books)

Stackoverflow, Go-nuts mailing list

Experience with Go

Building Go applications

CRUD App

API Client

Flickr, Weather API

Simple CRUD App using MySQL for data persistence

1st app: CRUD App

Sign up/Sign in

Read Status

Create Status

Delete Status

Edit Status

Sign out

MySQL

Basic Structure

package main

Import (“fmt”“net/http”

)

func handler(w http.ResponseWriter, r *http.Request) {fmt.Fprint(w, “hello world!”)

}

func main() {http.HandleFunc(“/”, handler)http.ListenAndServe(“:8080”, nil)

}

Basic Structure

package main

Import (“fmt”“net/http”

)

func handler(w http.ResponseWriter, r *http.Request) {fmt.Fprint(w, “hello world!”)

}

func main() {http.HandleFunc(“/”, handler)http.ListenAndServe(“:8080”, nil)

}Local server connection

Handler function when root is requested

Print output to client

All executable commands use package main

Go’s stdlib

Entry point

Libraries

import ("database/sql""html/template""fmt""log""net/http""os"_ "github.com/go-sql-driver/mysql""github.com/gorilla/mux""github.com/gorilla/securecookie”

)

Libraries

Standard library

import ("database/sql""html/template""fmt""log""net/http""os"_ "github.com/go-sql-driver/mysql""github.com/gorilla/mux""github.com/gorilla/securecookie”

)

External packages

Data Structs

Type Slice of Pointers to Post struct

type User struct {Userid int64Username stringPassword stringPosts []*Post

}

type Post struct {Tweetid stringUsername stringStatus string

}

Database functions

Return slice of slice of stringsfunc ReadStatus() (res [][]string) {err := db.Ping()if err != nil {

log.Fatal(err)}rows, err := db.Query("SELECT id, tweet, username FROM posts WHERE username = ? ORDER BY id DESC", currentuser)if err != nil {

log.Fatal(err)}defer rows.Close()

var tweet, id, username stringfor rows.Next() {

err := rows.Scan(&id, &tweet, &username)if err != nil {

return res}var a []stringa = append(a, id, tweet, username)res = append(res, a)

}return

}

Database functions

Return slice of slice of stringsfunc ReadStatus() (res [][]string) {err := db.Ping()if err != nil {

log.Fatal(err)}rows, err := db.Query("SELECT id, tweet, username FROM posts WHERE username = ? ORDER BY id DESC", currentuser)if err != nil {

log.Fatal(err)}defer rows.Close()

var tweet, id, username stringfor rows.Next() {

err := rows.Scan(&id, &tweet, &username)if err != nil {

return res}var a []stringa = append(a, id, tweet, username)res = append(res, a)

}return

}

Verify db connection

Raw queries

Append strings to sliceAppend slice of strings to output

Handler functions

Append slice of Post instances to Posts slice

func homeHandler(w http.ResponseWriter, r *http.Request) {currentuser = getUserName(r)if currentuser != "" {

var as []Posta := User{}m := ReadStatus()

for i := 0; i < len(m); i++ {as = append(as, Post{Tweetid: m[i][0], Username: currentuser, Status: m[i][1]})

}a = User{Username: currentuser}for i := 0; i < len(m); i++ {

a.Posts = append(a.Posts, &as[i])}

renderTemplate(w, "home", "homepage", a)} else {

http.Redirect(w, r, "/", 302)}

}

Wrapper func around html/template library

Create slice with Post instances

Func main

Open connection pool

Handlers for URL paths

func main() {db, err = sql.Open("mysql",

os.Getenv("DB_USERNAME")+":"+os.Getenv("DB_PASSWORD")+"@tcp("+os.Getenv("DB_CLEARDB")+":3306)/"+os.Getenv("DB_NAME"))

if err != nil {log.Fatal(err)

}defer db.Close()

router.HandleFunc("/", logHandler)router.HandleFunc("/login", loginHandler)router.HandleFunc("/home", homeHandler)router.HandleFunc("/home/tweets", usertweetHandler).Methods("POST")router.HandleFunc("/logout", logoutHandler).Methods("POST")router.HandleFunc("/home/delete", deleteHandler).Methods("POST")router.HandleFunc("/home/edit", editHandler).Methods("POST")router.HandleFunc("/home/save", saveHandler).Methods("POST”)router.PathPrefix("/").Handler(http.FileServer(http.Dir("./layout/")))http.Handle("/", router)

err := http.ListenAndServe(":"+os.Getenv("PORT"), nil)if err != nil {

panic(err)}

}

Port for server connection

2nd app: API Client

Get a series of photos from Flickrfor a random city and displaycurrent weather data for the samecity

Libraries

import ("encoding/json""fmt""html/template""io/ioutil""log""math/rand""net/http""os""strconv""time"

)

https://github.com/AudreyLim/weathergo

https://github.com/AudreyLim/twittergo

[email protected]

Twitter: @AudreyLim77

Thank you.