SlideShare ist ein Scribd-Unternehmen logo
1 von 44
Building Your First Web
App in Go
Andy Watson
Ionic Security
#ATOWebGo #ATO2015
All Things Open
2015
About Me
Who: Andy Watson
What: Code Flinger
Where: Ionic Security
http://ionic.com/ @andrewwatson
I used to write PHP
Lots of PHP.
Tons.
I’m a Gopher Now
Take the Tour at golang.org
Web Apps in Go
• No need for a wrapper like Apache or Nginx
• Create a self-contained, statically compiled
binary
• Cross Compile from your laptop to your
server architecture
Simple Web App
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello, worldn")
})
fmt.Print("Listening on :8080n")
http.ListenAndServe(":8080", nil)
}
Templates
Easily render well formed HTML using data
from your application
Nest templates inside each other (partials) for
easy re-use
Simple Template Example
func handleRoot(w http.ResponseWriter, req *http.Request) {
var templateStr =
"<html><body><h1>{{.}}</h1></body></html>n"
var templ =
template.Must(template.New("qr").Parse(templateStr))
templ.Execute(w, "Hello!")
}
func main() {
http.HandleFunc("/", handleRoot)
fmt.Print("Listening on :8080n")
http.ListenAndServe(":8080", nil)
}
Simple Logic
{{if .}}
<h1><a
href="{{.}}">Something!</a>
{{else}}
<h1>None</h1>
{{end}}
Iterations
type Book struct {
Author, Title string
}
func handler(w http.ResponseWriter, r *http.Request) {
// var bookList Book[]
bookList, err := lookupBooksForSale()
templ.Execute(w, bookList)
}
Template with range Operator
<h1>Books For Sale</h1>
{{range .}}
<h3>{{.Title}} by {{.Author}} </h3>
{{else}}
<h3>Sorry.</h3>
{{end}}
Outputs
<h3>Sorry.</h3> <h3>The Thing by
Stephen King</h3>
<h3>Moby Dick by
Herman Melville</h3>
With Empty List With Data
It’s the Methods, man!
func uploadHandler(…) {
if r.Method != "POST" {
err := doPostThings()
handleErrors(err)
return
}
}
Routing
Use a routing library like httprouter or mux to
match requests to handlers
Routes defined using paths and HTTP verbs
r := httprouter.New()
r.POST(”/login", LoginHandler)
r.GET("/", HomeHandler)
MiddleWare
Gets executed with every request
Used for logging, instrumentation, error
handling and more
Negroni
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "Welcome to the home page!")
})
n := negroni.Classic()
n.UseHandler(mux)
n.Run(":3000")
}
https://github.com/codegangsta/negroni
Negroni Classic
Common set of middleware
• Logging
• Recovery (from panics)
• Static Content Handling
Render
• Cleans Up boilerplate template rendering code
• Handles Errors
• Takes care of headers for HTML, JSON, XML
etc
https://github.com/unrolled/render
Context
• Stores values shared during a request
lifetime
• Useful for easily passing the full context of a
request to multiple handlers
http://www.gorillatoolkit.org/pkg/context
Sessions
Keep data between requests to maintain state
• User information
• Shopping Cart
• ETC
http://www.gorillatoolkit.org/pkg/sessions
Setting up Session Handling
var sessionstore = sessions.NewCookieStore([]byte(secret))
func init() {
sessionstore.Options = &sessions.Options{
Path: "/",
MaxAge: 3600,
HttpOnly: true,
}
}
Using Sessions
session, _ := sessionstore.Get(req, "OthrNumbr-session")
session.Values["loggedin"] = true
session.Values["cust_id"] = cust.CustomerId
session.Values["description"] = cust.Description
session.Save(req, w)
http.Redirect(w, req, "/home/", 302)
Rapid Development
• Gin wraps your process
• Recompiles and Restarts Automatically
• https://github.com/codegangsta/gin
Deploy to Production
• Cross Compile for Linux
• SCP to production
• Wrap in upstart script etc
Get up
and Go
Contain Yourself
The GoLang library Docker images make it
easy to build and run your Go app in a
container
https://hub.docker.com/_/golang/
Dockerfile
FROM golang:1.5-onbuild
Docker Commands
$ docker build -t hello-world .
$ docker run --rm -it --name fred hello-world
Google App Engine
• GAE supports Go runtime
• Automatically scales up instances
• Provides highly available datastore
• Supports Go 1.4 at this time
• Soon: Migrate GAE to Managed VMs
https://cloud.google.com/appengine/
GAE DataStore
type Greeting struct {
Author string
Content string
Date time.Time
}
Fetch from DataStore
func root(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
q := datastore.NewQuery("Greeting").
Ancestor(guestbookKey(c)).Order("-Date").Limit(10)
greetings := make([]Greeting, 0, 10)
if _, err := q.GetAll(c, &greetings); err != nil {
http.Error(w, err.Error(),500)
return
}
}
GAE Example
https://github.com/GoogleCloudPlatform/appen
gine-guestbook-go
Shows session handling, data storage,
authentication and more
Other Resources
Building Web Apps with Go – by codegangtsa
http://bit.ly/WebAppsWithGo
Google Cloud Platform - Go
http://bit.ly/GoGoogleCloud
Deployed To GAE
SMS Voting Application for CSS Dev Conf
• Takes votes via SMS (Twilio) and stores
them in GAE Datastore
• Outputs them as CSV
Deployed to GAE
OthrNumbr
• Burner Numbers for
texting with strangers
• Written in Go, Deployed
on App Engine
• Users Datastore,
memcache, Twilio, Stripe
http://othrnumbr.com/
@andrewwatson
http://about.me/andrewwatson
Thank You
Kitty wants to learn concurrency
Concurrency in Go
• In Go, concurrency is accomplished by
passing shared values around on channels
• Not by sharing memory between threads
Repeat After Me
“Do not communicate by sharing
memory; instead, share memory by
communicating.”
Concurrent Routines
Created by putting “go” in front of function calls
func Announce(message string, delay time.Duration) {
go func() {
time.Sleep(delay)
fmt.Println(message)
}() // Note the parentheses - must call the function.
}
https://golang.org/doc/effective_go.html#concurrency
Channels
Go has a built in primitive types for
communicating between goroutines
c := make(chan int) // Allocate a channel.
// Start the sort in a goroutine; when it completes, signal on the channel.
go func() {
list.Sort()
c <- 1 // Send a signal; value does not matter.
}()
doSomethingForAWhile()
<-c // Wait for sort to finish; discard sent value.
Channels
• Can be buffered or unbuffered
• Can be declared to carry any other type,
even channels!
Concurrency in Go
The essential guides:
http://bit.ly/ConcurrentGo
http://bit.ly/AdvancedGoConcurrency

Weitere ähnliche Inhalte

Was ist angesagt?

Open stack swift architecture and monitoring
Open stack swift architecture and monitoringOpen stack swift architecture and monitoring
Open stack swift architecture and monitoringKavit Munshi
 
2 Day Bootcamp for OpenStack--Cloud Training by Mirantis (Preview)
2 Day Bootcamp for OpenStack--Cloud Training by Mirantis (Preview)2 Day Bootcamp for OpenStack--Cloud Training by Mirantis (Preview)
2 Day Bootcamp for OpenStack--Cloud Training by Mirantis (Preview)Mirantis
 
Cloud Computing Open Stack Compute Node
Cloud Computing Open Stack Compute NodeCloud Computing Open Stack Compute Node
Cloud Computing Open Stack Compute NodePalak Sood
 
OpenStack Introduction
OpenStack IntroductionOpenStack Introduction
OpenStack Introductionopenstackindia
 
An Introduction to OpenStack
An Introduction to OpenStackAn Introduction to OpenStack
An Introduction to OpenStackScott Lowe
 
Kubernetes security and you
Kubernetes security and youKubernetes security and you
Kubernetes security and youKarthik Gaekwad
 
Structured Container Delivery by Oscar Renalias, Accenture
Structured Container Delivery by Oscar Renalias, AccentureStructured Container Delivery by Oscar Renalias, Accenture
Structured Container Delivery by Oscar Renalias, AccentureDocker, Inc.
 
Infrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and OpsInfrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and OpsMykyta Protsenko
 
Security model for a remote company
Security model for a remote companySecurity model for a remote company
Security model for a remote companyPierre Mavro
 
KURMA - A Containerized Container Platform - KubeCon 2016
KURMA - A Containerized Container Platform - KubeCon 2016KURMA - A Containerized Container Platform - KubeCon 2016
KURMA - A Containerized Container Platform - KubeCon 2016Apcera
 
The Future of SDN in CloudStack by Chiradeep Vittal
The Future of SDN in CloudStack by Chiradeep VittalThe Future of SDN in CloudStack by Chiradeep Vittal
The Future of SDN in CloudStack by Chiradeep Vittalbuildacloud
 
Kubernetes Summit 2019 - Harden Your Kubernetes Cluster
Kubernetes Summit 2019 - Harden Your Kubernetes ClusterKubernetes Summit 2019 - Harden Your Kubernetes Cluster
Kubernetes Summit 2019 - Harden Your Kubernetes Clustersmalltown
 
Introduction to OpenStack : Barcamp Bangkhen 2016
Introduction to OpenStack : Barcamp Bangkhen 2016Introduction to OpenStack : Barcamp Bangkhen 2016
Introduction to OpenStack : Barcamp Bangkhen 2016Opsta
 
New Features of Kubernetes v1.2.0 beta
New Features of Kubernetes v1.2.0 betaNew Features of Kubernetes v1.2.0 beta
New Features of Kubernetes v1.2.0 betaGiragadurai Vallirajan
 
OpenStack Cloud Tutorial | What is OpenStack | OpenStack Tutorial | OpenStack...
OpenStack Cloud Tutorial | What is OpenStack | OpenStack Tutorial | OpenStack...OpenStack Cloud Tutorial | What is OpenStack | OpenStack Tutorial | OpenStack...
OpenStack Cloud Tutorial | What is OpenStack | OpenStack Tutorial | OpenStack...Edureka!
 
Introduction to cloud and openstack
Introduction to cloud and openstackIntroduction to cloud and openstack
Introduction to cloud and openstackShivaling Sannalli
 
Vancouver open stack meetup presentation
Vancouver open stack meetup presentationVancouver open stack meetup presentation
Vancouver open stack meetup presentationSean Winn
 
Openstack - An introduction/Installation - Presented at Dr Dobb's conference...
 Openstack - An introduction/Installation - Presented at Dr Dobb's conference... Openstack - An introduction/Installation - Presented at Dr Dobb's conference...
Openstack - An introduction/Installation - Presented at Dr Dobb's conference...Rahul Krishna Upadhyaya
 
Building Angular 2.0 applications with TypeScript
Building Angular 2.0 applications with TypeScriptBuilding Angular 2.0 applications with TypeScript
Building Angular 2.0 applications with TypeScriptMSDEVMTL
 

Was ist angesagt? (20)

Open stack swift architecture and monitoring
Open stack swift architecture and monitoringOpen stack swift architecture and monitoring
Open stack swift architecture and monitoring
 
2 Day Bootcamp for OpenStack--Cloud Training by Mirantis (Preview)
2 Day Bootcamp for OpenStack--Cloud Training by Mirantis (Preview)2 Day Bootcamp for OpenStack--Cloud Training by Mirantis (Preview)
2 Day Bootcamp for OpenStack--Cloud Training by Mirantis (Preview)
 
Cloud Computing Open Stack Compute Node
Cloud Computing Open Stack Compute NodeCloud Computing Open Stack Compute Node
Cloud Computing Open Stack Compute Node
 
OpenStack Introduction
OpenStack IntroductionOpenStack Introduction
OpenStack Introduction
 
An Introduction to OpenStack
An Introduction to OpenStackAn Introduction to OpenStack
An Introduction to OpenStack
 
Kubernetes security and you
Kubernetes security and youKubernetes security and you
Kubernetes security and you
 
Structured Container Delivery by Oscar Renalias, Accenture
Structured Container Delivery by Oscar Renalias, AccentureStructured Container Delivery by Oscar Renalias, Accenture
Structured Container Delivery by Oscar Renalias, Accenture
 
Infrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and OpsInfrastructure-as-code: bridging the gap between Devs and Ops
Infrastructure-as-code: bridging the gap between Devs and Ops
 
Security model for a remote company
Security model for a remote companySecurity model for a remote company
Security model for a remote company
 
KURMA - A Containerized Container Platform - KubeCon 2016
KURMA - A Containerized Container Platform - KubeCon 2016KURMA - A Containerized Container Platform - KubeCon 2016
KURMA - A Containerized Container Platform - KubeCon 2016
 
The Future of SDN in CloudStack by Chiradeep Vittal
The Future of SDN in CloudStack by Chiradeep VittalThe Future of SDN in CloudStack by Chiradeep Vittal
The Future of SDN in CloudStack by Chiradeep Vittal
 
Kubernetes Summit 2019 - Harden Your Kubernetes Cluster
Kubernetes Summit 2019 - Harden Your Kubernetes ClusterKubernetes Summit 2019 - Harden Your Kubernetes Cluster
Kubernetes Summit 2019 - Harden Your Kubernetes Cluster
 
Introduction to OpenStack : Barcamp Bangkhen 2016
Introduction to OpenStack : Barcamp Bangkhen 2016Introduction to OpenStack : Barcamp Bangkhen 2016
Introduction to OpenStack : Barcamp Bangkhen 2016
 
New Features of Kubernetes v1.2.0 beta
New Features of Kubernetes v1.2.0 betaNew Features of Kubernetes v1.2.0 beta
New Features of Kubernetes v1.2.0 beta
 
OpenStack Cloud Tutorial | What is OpenStack | OpenStack Tutorial | OpenStack...
OpenStack Cloud Tutorial | What is OpenStack | OpenStack Tutorial | OpenStack...OpenStack Cloud Tutorial | What is OpenStack | OpenStack Tutorial | OpenStack...
OpenStack Cloud Tutorial | What is OpenStack | OpenStack Tutorial | OpenStack...
 
Introduction to cloud and openstack
Introduction to cloud and openstackIntroduction to cloud and openstack
Introduction to cloud and openstack
 
CloudStack Clients and Tools
CloudStack Clients and ToolsCloudStack Clients and Tools
CloudStack Clients and Tools
 
Vancouver open stack meetup presentation
Vancouver open stack meetup presentationVancouver open stack meetup presentation
Vancouver open stack meetup presentation
 
Openstack - An introduction/Installation - Presented at Dr Dobb's conference...
 Openstack - An introduction/Installation - Presented at Dr Dobb's conference... Openstack - An introduction/Installation - Presented at Dr Dobb's conference...
Openstack - An introduction/Installation - Presented at Dr Dobb's conference...
 
Building Angular 2.0 applications with TypeScript
Building Angular 2.0 applications with TypeScriptBuilding Angular 2.0 applications with TypeScript
Building Angular 2.0 applications with TypeScript
 

Ähnlich wie How to Build Your First Web App in Go

Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSocketsGonzalo Ayuso
 
1.6 米嘉 gobuildweb
1.6 米嘉 gobuildweb1.6 米嘉 gobuildweb
1.6 米嘉 gobuildwebLeo Zhou
 
Building TweetEngine
Building TweetEngineBuilding TweetEngine
Building TweetEngineikailan
 
Web Standards Support in WebKit
Web Standards Support in WebKitWeb Standards Support in WebKit
Web Standards Support in WebKitJoone Hur
 
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineYared Ayalew
 
CouchDB for Web Applications - Erlang Factory London 2009
CouchDB for Web Applications - Erlang Factory London 2009CouchDB for Web Applications - Erlang Factory London 2009
CouchDB for Web Applications - Erlang Factory London 2009Jason Davies
 
Php on the Web and Desktop
Php on the Web and DesktopPhp on the Web and Desktop
Php on the Web and DesktopElizabeth Smith
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2Asher Martin
 
Notes on SF W3Conf
Notes on SF W3ConfNotes on SF W3Conf
Notes on SF W3ConfEdy Dawson
 
HTML5: An Overview
HTML5: An OverviewHTML5: An Overview
HTML5: An OverviewNagendra Um
 
HTML5 (and friends) - History, overview and current status - jsDay Verona 11....
HTML5 (and friends) - History, overview and current status - jsDay Verona 11....HTML5 (and friends) - History, overview and current status - jsDay Verona 11....
HTML5 (and friends) - History, overview and current status - jsDay Verona 11....Patrick Lauke
 
HTML5 vs Silverlight
HTML5 vs SilverlightHTML5 vs Silverlight
HTML5 vs SilverlightMatt Casto
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to TornadoGavin Roy
 
SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...
SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...
SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...Sencha
 
Introduction to Ethereum
Introduction to EthereumIntroduction to Ethereum
Introduction to EthereumArnold Pham
 
HTML5 on Mobile
HTML5 on MobileHTML5 on Mobile
HTML5 on MobileAdam Lu
 
Performance Metrics in a Day with Selenium
Performance Metrics in a Day with SeleniumPerformance Metrics in a Day with Selenium
Performance Metrics in a Day with SeleniumMark Watson
 

Ähnlich wie How to Build Your First Web App in Go (20)

Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
1.6 米嘉 gobuildweb
1.6 米嘉 gobuildweb1.6 米嘉 gobuildweb
1.6 米嘉 gobuildweb
 
Building TweetEngine
Building TweetEngineBuilding TweetEngine
Building TweetEngine
 
Web Standards Support in WebKit
Web Standards Support in WebKitWeb Standards Support in WebKit
Web Standards Support in WebKit
 
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App Engine
 
CouchDB for Web Applications - Erlang Factory London 2009
CouchDB for Web Applications - Erlang Factory London 2009CouchDB for Web Applications - Erlang Factory London 2009
CouchDB for Web Applications - Erlang Factory London 2009
 
Php on the Web and Desktop
Php on the Web and DesktopPhp on the Web and Desktop
Php on the Web and Desktop
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Azure F#unctions
Azure F#unctionsAzure F#unctions
Azure F#unctions
 
Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2
 
Notes on SF W3Conf
Notes on SF W3ConfNotes on SF W3Conf
Notes on SF W3Conf
 
CGI by rj
CGI by rjCGI by rj
CGI by rj
 
HTML5: An Overview
HTML5: An OverviewHTML5: An Overview
HTML5: An Overview
 
HTML5 (and friends) - History, overview and current status - jsDay Verona 11....
HTML5 (and friends) - History, overview and current status - jsDay Verona 11....HTML5 (and friends) - History, overview and current status - jsDay Verona 11....
HTML5 (and friends) - History, overview and current status - jsDay Verona 11....
 
HTML5 vs Silverlight
HTML5 vs SilverlightHTML5 vs Silverlight
HTML5 vs Silverlight
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to Tornado
 
SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...
SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...
SenchaCon 2016: A Look Ahead: Survey Next-Gen Modern Browser APIs - Shikhir S...
 
Introduction to Ethereum
Introduction to EthereumIntroduction to Ethereum
Introduction to Ethereum
 
HTML5 on Mobile
HTML5 on MobileHTML5 on Mobile
HTML5 on Mobile
 
Performance Metrics in a Day with Selenium
Performance Metrics in a Day with SeleniumPerformance Metrics in a Day with Selenium
Performance Metrics in a Day with Selenium
 

Mehr von All Things Open

Building Reliability - The Realities of Observability
Building Reliability - The Realities of ObservabilityBuilding Reliability - The Realities of Observability
Building Reliability - The Realities of ObservabilityAll Things Open
 
Modern Database Best Practices
Modern Database Best PracticesModern Database Best Practices
Modern Database Best PracticesAll Things Open
 
Open Source and Public Policy
Open Source and Public PolicyOpen Source and Public Policy
Open Source and Public PolicyAll Things Open
 
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...All Things Open
 
The State of Passwordless Auth on the Web - Phil Nash
The State of Passwordless Auth on the Web - Phil NashThe State of Passwordless Auth on the Web - Phil Nash
The State of Passwordless Auth on the Web - Phil NashAll Things Open
 
Total ReDoS: The dangers of regex in JavaScript
Total ReDoS: The dangers of regex in JavaScriptTotal ReDoS: The dangers of regex in JavaScript
Total ReDoS: The dangers of regex in JavaScriptAll Things Open
 
What Does Real World Mass Adoption of Decentralized Tech Look Like?
What Does Real World Mass Adoption of Decentralized Tech Look Like?What Does Real World Mass Adoption of Decentralized Tech Look Like?
What Does Real World Mass Adoption of Decentralized Tech Look Like?All Things Open
 
How to Write & Deploy a Smart Contract
How to Write & Deploy a Smart ContractHow to Write & Deploy a Smart Contract
How to Write & Deploy a Smart ContractAll Things Open
 
Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
 Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlowAll Things Open
 
DEI Challenges and Success
DEI Challenges and SuccessDEI Challenges and Success
DEI Challenges and SuccessAll Things Open
 
Scaling Web Applications with Background
Scaling Web Applications with BackgroundScaling Web Applications with Background
Scaling Web Applications with BackgroundAll Things Open
 
Supercharging tutorials with WebAssembly
Supercharging tutorials with WebAssemblySupercharging tutorials with WebAssembly
Supercharging tutorials with WebAssemblyAll Things Open
 
Using SQL to Find Needles in Haystacks
Using SQL to Find Needles in HaystacksUsing SQL to Find Needles in Haystacks
Using SQL to Find Needles in HaystacksAll Things Open
 
Configuration Security as a Game of Pursuit Intercept
Configuration Security as a Game of Pursuit InterceptConfiguration Security as a Game of Pursuit Intercept
Configuration Security as a Game of Pursuit InterceptAll Things Open
 
Scaling an Open Source Sponsorship Program
Scaling an Open Source Sponsorship ProgramScaling an Open Source Sponsorship Program
Scaling an Open Source Sponsorship ProgramAll Things Open
 
Build Developer Experience Teams for Open Source
Build Developer Experience Teams for Open SourceBuild Developer Experience Teams for Open Source
Build Developer Experience Teams for Open SourceAll Things Open
 
Deploying Models at Scale with Apache Beam
Deploying Models at Scale with Apache BeamDeploying Models at Scale with Apache Beam
Deploying Models at Scale with Apache BeamAll Things Open
 
Sudo – Giving access while staying in control
Sudo – Giving access while staying in controlSudo – Giving access while staying in control
Sudo – Giving access while staying in controlAll Things Open
 
Fortifying the Future: Tackling Security Challenges in AI/ML Applications
Fortifying the Future: Tackling Security Challenges in AI/ML ApplicationsFortifying the Future: Tackling Security Challenges in AI/ML Applications
Fortifying the Future: Tackling Security Challenges in AI/ML ApplicationsAll Things Open
 
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...All Things Open
 

Mehr von All Things Open (20)

Building Reliability - The Realities of Observability
Building Reliability - The Realities of ObservabilityBuilding Reliability - The Realities of Observability
Building Reliability - The Realities of Observability
 
Modern Database Best Practices
Modern Database Best PracticesModern Database Best Practices
Modern Database Best Practices
 
Open Source and Public Policy
Open Source and Public PolicyOpen Source and Public Policy
Open Source and Public Policy
 
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
 
The State of Passwordless Auth on the Web - Phil Nash
The State of Passwordless Auth on the Web - Phil NashThe State of Passwordless Auth on the Web - Phil Nash
The State of Passwordless Auth on the Web - Phil Nash
 
Total ReDoS: The dangers of regex in JavaScript
Total ReDoS: The dangers of regex in JavaScriptTotal ReDoS: The dangers of regex in JavaScript
Total ReDoS: The dangers of regex in JavaScript
 
What Does Real World Mass Adoption of Decentralized Tech Look Like?
What Does Real World Mass Adoption of Decentralized Tech Look Like?What Does Real World Mass Adoption of Decentralized Tech Look Like?
What Does Real World Mass Adoption of Decentralized Tech Look Like?
 
How to Write & Deploy a Smart Contract
How to Write & Deploy a Smart ContractHow to Write & Deploy a Smart Contract
How to Write & Deploy a Smart Contract
 
Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
 Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
 
DEI Challenges and Success
DEI Challenges and SuccessDEI Challenges and Success
DEI Challenges and Success
 
Scaling Web Applications with Background
Scaling Web Applications with BackgroundScaling Web Applications with Background
Scaling Web Applications with Background
 
Supercharging tutorials with WebAssembly
Supercharging tutorials with WebAssemblySupercharging tutorials with WebAssembly
Supercharging tutorials with WebAssembly
 
Using SQL to Find Needles in Haystacks
Using SQL to Find Needles in HaystacksUsing SQL to Find Needles in Haystacks
Using SQL to Find Needles in Haystacks
 
Configuration Security as a Game of Pursuit Intercept
Configuration Security as a Game of Pursuit InterceptConfiguration Security as a Game of Pursuit Intercept
Configuration Security as a Game of Pursuit Intercept
 
Scaling an Open Source Sponsorship Program
Scaling an Open Source Sponsorship ProgramScaling an Open Source Sponsorship Program
Scaling an Open Source Sponsorship Program
 
Build Developer Experience Teams for Open Source
Build Developer Experience Teams for Open SourceBuild Developer Experience Teams for Open Source
Build Developer Experience Teams for Open Source
 
Deploying Models at Scale with Apache Beam
Deploying Models at Scale with Apache BeamDeploying Models at Scale with Apache Beam
Deploying Models at Scale with Apache Beam
 
Sudo – Giving access while staying in control
Sudo – Giving access while staying in controlSudo – Giving access while staying in control
Sudo – Giving access while staying in control
 
Fortifying the Future: Tackling Security Challenges in AI/ML Applications
Fortifying the Future: Tackling Security Challenges in AI/ML ApplicationsFortifying the Future: Tackling Security Challenges in AI/ML Applications
Fortifying the Future: Tackling Security Challenges in AI/ML Applications
 
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
 

Kürzlich hochgeladen

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 

Kürzlich hochgeladen (20)

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 

How to Build Your First Web App in Go

  • 1. Building Your First Web App in Go Andy Watson Ionic Security #ATOWebGo #ATO2015 All Things Open 2015
  • 2. About Me Who: Andy Watson What: Code Flinger Where: Ionic Security http://ionic.com/ @andrewwatson
  • 3. I used to write PHP Lots of PHP. Tons.
  • 5. Take the Tour at golang.org
  • 6. Web Apps in Go • No need for a wrapper like Apache or Nginx • Create a self-contained, statically compiled binary • Cross Compile from your laptop to your server architecture
  • 7. Simple Web App package main import ( "fmt" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello, worldn") }) fmt.Print("Listening on :8080n") http.ListenAndServe(":8080", nil) }
  • 8. Templates Easily render well formed HTML using data from your application Nest templates inside each other (partials) for easy re-use
  • 9. Simple Template Example func handleRoot(w http.ResponseWriter, req *http.Request) { var templateStr = "<html><body><h1>{{.}}</h1></body></html>n" var templ = template.Must(template.New("qr").Parse(templateStr)) templ.Execute(w, "Hello!") } func main() { http.HandleFunc("/", handleRoot) fmt.Print("Listening on :8080n") http.ListenAndServe(":8080", nil) }
  • 11. Iterations type Book struct { Author, Title string } func handler(w http.ResponseWriter, r *http.Request) { // var bookList Book[] bookList, err := lookupBooksForSale() templ.Execute(w, bookList) }
  • 12. Template with range Operator <h1>Books For Sale</h1> {{range .}} <h3>{{.Title}} by {{.Author}} </h3> {{else}} <h3>Sorry.</h3> {{end}}
  • 13. Outputs <h3>Sorry.</h3> <h3>The Thing by Stephen King</h3> <h3>Moby Dick by Herman Melville</h3> With Empty List With Data
  • 14. It’s the Methods, man! func uploadHandler(…) { if r.Method != "POST" { err := doPostThings() handleErrors(err) return } }
  • 15. Routing Use a routing library like httprouter or mux to match requests to handlers Routes defined using paths and HTTP verbs r := httprouter.New() r.POST(”/login", LoginHandler) r.GET("/", HomeHandler)
  • 16. MiddleWare Gets executed with every request Used for logging, instrumentation, error handling and more
  • 17. Negroni func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Welcome to the home page!") }) n := negroni.Classic() n.UseHandler(mux) n.Run(":3000") } https://github.com/codegangsta/negroni
  • 18. Negroni Classic Common set of middleware • Logging • Recovery (from panics) • Static Content Handling
  • 19. Render • Cleans Up boilerplate template rendering code • Handles Errors • Takes care of headers for HTML, JSON, XML etc https://github.com/unrolled/render
  • 20. Context • Stores values shared during a request lifetime • Useful for easily passing the full context of a request to multiple handlers http://www.gorillatoolkit.org/pkg/context
  • 21. Sessions Keep data between requests to maintain state • User information • Shopping Cart • ETC http://www.gorillatoolkit.org/pkg/sessions
  • 22. Setting up Session Handling var sessionstore = sessions.NewCookieStore([]byte(secret)) func init() { sessionstore.Options = &sessions.Options{ Path: "/", MaxAge: 3600, HttpOnly: true, } }
  • 23. Using Sessions session, _ := sessionstore.Get(req, "OthrNumbr-session") session.Values["loggedin"] = true session.Values["cust_id"] = cust.CustomerId session.Values["description"] = cust.Description session.Save(req, w) http.Redirect(w, req, "/home/", 302)
  • 24. Rapid Development • Gin wraps your process • Recompiles and Restarts Automatically • https://github.com/codegangsta/gin
  • 25. Deploy to Production • Cross Compile for Linux • SCP to production • Wrap in upstart script etc
  • 27. Contain Yourself The GoLang library Docker images make it easy to build and run your Go app in a container https://hub.docker.com/_/golang/
  • 29. Docker Commands $ docker build -t hello-world . $ docker run --rm -it --name fred hello-world
  • 30. Google App Engine • GAE supports Go runtime • Automatically scales up instances • Provides highly available datastore • Supports Go 1.4 at this time • Soon: Migrate GAE to Managed VMs https://cloud.google.com/appengine/
  • 31. GAE DataStore type Greeting struct { Author string Content string Date time.Time }
  • 32. Fetch from DataStore func root(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) q := datastore.NewQuery("Greeting"). Ancestor(guestbookKey(c)).Order("-Date").Limit(10) greetings := make([]Greeting, 0, 10) if _, err := q.GetAll(c, &greetings); err != nil { http.Error(w, err.Error(),500) return } }
  • 34. Other Resources Building Web Apps with Go – by codegangtsa http://bit.ly/WebAppsWithGo Google Cloud Platform - Go http://bit.ly/GoGoogleCloud
  • 35. Deployed To GAE SMS Voting Application for CSS Dev Conf • Takes votes via SMS (Twilio) and stores them in GAE Datastore • Outputs them as CSV
  • 36. Deployed to GAE OthrNumbr • Burner Numbers for texting with strangers • Written in Go, Deployed on App Engine • Users Datastore, memcache, Twilio, Stripe http://othrnumbr.com/
  • 38. Kitty wants to learn concurrency
  • 39. Concurrency in Go • In Go, concurrency is accomplished by passing shared values around on channels • Not by sharing memory between threads
  • 40. Repeat After Me “Do not communicate by sharing memory; instead, share memory by communicating.”
  • 41. Concurrent Routines Created by putting “go” in front of function calls func Announce(message string, delay time.Duration) { go func() { time.Sleep(delay) fmt.Println(message) }() // Note the parentheses - must call the function. } https://golang.org/doc/effective_go.html#concurrency
  • 42. Channels Go has a built in primitive types for communicating between goroutines c := make(chan int) // Allocate a channel. // Start the sort in a goroutine; when it completes, signal on the channel. go func() { list.Sort() c <- 1 // Send a signal; value does not matter. }() doSomethingForAWhile() <-c // Wait for sort to finish; discard sent value.
  • 43. Channels • Can be buffered or unbuffered • Can be declared to carry any other type, even channels!
  • 44. Concurrency in Go The essential guides: http://bit.ly/ConcurrentGo http://bit.ly/AdvancedGoConcurrency

Hinweis der Redaktion

  1. Hello everyone, thank you for coming. I’m Andy Watson and I’m here to talk to you about ways to use cryptography correctly in your applications
  2. I’m currently a senior engineer at Ionic Security which is a data protection security company based out of Atlanta, GA I’ve been a software developer professionally since 1996 when I got my first job developing large scale, distributed systems for processing streams of data collected out of particle accelerators with some Physics professors at FSU. This was “cloud” computing before it had a name. Since then I’ve built mobile, desktop and web applications for companies like The Walt Disney World Resort, Maersk Sealand, Cox Communications, CoffeeCup Software and many many others.