SlideShare uma empresa Scribd logo
1 de 20
Baixar para ler offline
Lessons Learned from Building a
REST API on Google App Engine
Jonathan Altman
Presentation to GolangDC-October 29, 2015
Whitenoise Market Webapp
• White Noise by TMSoft (http://www.tmsoft.com/white-noise/) is the
leading sleeping app for iOS,Android, Mac, and Windows
• Customer wanted a way to:
• Allow users to download additional content to the app
• Create a vibrant community for users to interact with each other
• Scale to the large demand of existing users
White Noise Market App
Project
• Build a RESTful API to drive Whitenoise Market’s web front-end
• Angular SPA front end, also built as part of the project
• User authentication with Google or Facebook account—OAuth2
• Role-based authorization
• Implied: customer will use the API from a native mobile client as well
• Golang on Google App Engine, leverage their APIs
Sample Calls
• GET /api/items — get all items
• GET /api/item/item_id — get data about the item with id item_id
GAE via Golang
• Project was approx. 6 person/weeks 2nd 1/2 2014, including front end
• Customer specification based on their research
• Inherited solid proof of concept app, but no firm API
• GAE golang support was still beta, long term support indeterminate
• Actual GAE API usage calls: outside the scope of this talk (but see
https://cloud.google.com/appengine/docs/go/)
Issues
• Package management
• Routing
• REST response formulation/error logging
• OAuth2 support for providers other than Google
• Authorization
• Miscellaneous
Package Management
• goapp get not go get
• Not building an exe locally, packages need to be in source tree
uploaded to GAE - feels weird compared to golang philosophy
Routing — GAE has choices
• Prefix hostname with module — exposing internals
• Dispatch file: dispatch.yaml — 10 routing rules max
• Roll your own — just start matching URLs in the main dispatch
handler in your golang code
• or…
• and remember: Google Cloud Endpoints were not yet a thing.
Probably the way to go today
RollYour Own Router
3rd Party Router: Gorilla mux!
• http://www.gorillatoolkit.org/pkg/mux
• Gorilla web toolkit has a bunch of other nice parts
• Other 3rd party router libraries probably work fine
• Parameterization, method control
• GAE takes care of a lot of other things Gorilla toolkit provides
r.HandleFunc("/api/comments/{sid}",	
  handleGetComments).Methods("GET")

r.HandleFunc(“/api/comments/{sid}",	
  aihttphelper.AuthenticatedEndpoint(HandleAddComment)).Methods("PUT")
REST Status/Response Logging
• Standard REST success and error responses
• gorca — https://github.com/icub3d/gorca
• gorca.LogAndMessage: Logs console message and returns short
message plus status code
• gorca.WriteJSON: succesful responses
gorca.LogAndMessage(c,	
  w,	
  r,	
  err,	
  "error",	
  "not_authenticated",	
  http.StatusUnauthorized)	
  
gorca.LogAndMessage(c,	
  w,	
  r,	
  err,	
  "error",	
  err.Error(),	
  http.StatusBadRequest)	
  
gorca.WriteJSON(c,	
  w,	
  r,	
  map[string]interface{}{“status”:	
  "OK",	
  "tagAdded":	
  tagValue})	
  
OAuth2 Support - gomniauth
• GAE does OAuth2 authentication…only for Google
• gomniauth does OAuth2 authentication for multiple providers,
including google (https://github.com/stretchr/gomniauth)
• jwt for HTTP Bearer Token — (https://github.com/dgrijalva/jwt-go)
• Accepted pull request in gomniauth allows setting http Transport used
because the GAE runtime replaces net/http’s DefaultTransport with a
context-based one https://github.com/stretchr/gomniauth/pull/23)
gomniauth Patch
• You have to fetch a Transport with the current requests’ GAE context,
and pass that to gomniauth before doing authentication
• See https://github.com/jonathana/gomniauth/commit/
3e2e23995b035e26bbd58a0f56cb2b2d61dbe993 for details/usage
Authorization
• Separate from authentication. What a user can do, once we know
who the user is
• Wrapper function shown before:
• “Middleware” takes a target function with an extra argument beyond
the normal HTTP request handler for the authenticated user
information, and returns a normal HTTP handler function that does
the authorization check and runs the target function if authorized
• Factory functions encapsulated role info, but could pass in ACL data
r.HandleFunc(“/api/comments/{sid}",	
  aihttphelper.AuthenticatedEndpoint(HandleAddComment)).Methods("PUT")
Authorization Middlewaretype	
  AiHandlerFunc	
  func(appengine.Context,	
  http.ResponseWriter,	
  *http.Request,	
  *aitypes.AIUserInfo)	
  
func	
  generateAuthenticatedEndpoint(h	
  AiHandlerFunc,	
  requiredRoles	
  aitypes.RoleValue)	
  http.HandlerFunc	
  {

	
   return	
  func(w	
  http.ResponseWriter,	
  r	
  *http.Request)	
  {

	
   	
   c	
  :=	
  appengine.NewContext(r)

	
   

	
   	
   authUser,	
  err	
  :=	
  AuthenticateRequest(c,	
  r)

	
   	
   if	
  (err	
  !=	
  nil)	
  {

	
   	
   	
   gorca.LogAndFailed(c,	
  w,	
  r,	
  err)

	
   	
   	
   return

	
   	
   }

	
   	
   //	
  401	
  User	
  not	
  authenticated	
  	
   if	
  (authUser	
  ==	
  nil)	
  {

	
   	
   	
   http.Error(w,	
  "",	
  http.StatusUnauthorized)

	
   	
   	
   return

	
   	
   }

	
   	
   //	
  403	
  User	
  not	
  authorized	
  (authenticated,	
  but	
  no	
  permission	
  to	
  resource)

	
   	
   if	
  (requiredRoles	
  >	
  0	
  &&	
  !(hasRole(authUser,	
  requiredRoles))	
  {

	
   	
   	
   http.Error(w,	
  "",	
  http.StatusForbidden)

	
   	
   	
   return

	
   	
   }

	
   

	
   	
   //	
  User	
  is	
  authenticated	
  and	
  authorized

	
   	
   h(c,	
  w,	
  r,	
  authUser)

	
   }

}	
  
func	
  AuthenticatedEndpoint(h	
  WnHandlerFunc)	
  http.HandlerFunc	
  {

	
   return	
  generateAuthenticatedEndpoint(h,	
  0)

}
Miscellaneous
• Concurrency: ignored as a premature optimization. Issues with
urlfetch.Transport led to concern on runtime support/research time
• GAE API deprecation: not golang specific, but several APIs in use were
deprecated post-project and had to be replaced (blobstore)
• GAE appears to be going to more of an a la carte model where
existing components are replaced with general GCE equivalents
• Google Cloud Endpoints were not available at the time
Miscellaneous, cont.
• You’ll be playing with the JSON serialization properties. Javascript<-
>go naming rules mismatch: nobody wants Javascript properties to
begin with capital letters. Also, I tend to prefer map[string]interface{}
over defined structs where I can
• Using appengine.Context. You will need to, almost everywhere,
whether it’s for working with datastore, making outbound http
requests, or logging via its .Infof() call
ThankYou!
email: jonathan@async.io
github: jonathana
twitter: @async_io

Mais conteúdo relacionado

Mais procurados

JAX 2013: Introducing Eclipse Orion
JAX 2013: Introducing Eclipse OrionJAX 2013: Introducing Eclipse Orion
JAX 2013: Introducing Eclipse Orion
martinlippert
 

Mais procurados (13)

One code Web, iOS, Android
One code Web, iOS, AndroidOne code Web, iOS, Android
One code Web, iOS, Android
 
A User Interface for adding Machine Learning tools into GitHub
A User Interface for adding Machine Learning tools into GitHubA User Interface for adding Machine Learning tools into GitHub
A User Interface for adding Machine Learning tools into GitHub
 
JHipster
JHipsterJHipster
JHipster
 
Ktor 部署攻略 - 老派 Fat Jar 大法
Ktor 部署攻略 - 老派 Fat Jar 大法Ktor 部署攻略 - 老派 Fat Jar 大法
Ktor 部署攻略 - 老派 Fat Jar 大法
 
2d web mapping with flask
2d web mapping with flask2d web mapping with flask
2d web mapping with flask
 
JAX 2013: Introducing Eclipse Orion
JAX 2013: Introducing Eclipse OrionJAX 2013: Introducing Eclipse Orion
JAX 2013: Introducing Eclipse Orion
 
PyCon Israel - Launch Jupyter to the Cloud
PyCon Israel - Launch Jupyter to the CloudPyCon Israel - Launch Jupyter to the Cloud
PyCon Israel - Launch Jupyter to the Cloud
 
Spring Tooling: What's new and what's coming
Spring Tooling: What's new and what's comingSpring Tooling: What's new and what's coming
Spring Tooling: What's new and what's coming
 
Azkaban
AzkabanAzkaban
Azkaban
 
Apache Airflow
Apache AirflowApache Airflow
Apache Airflow
 
Automate your business
Automate your businessAutomate your business
Automate your business
 
用 OPENRNDR 將 Chatbot 訊息視覺化
用 OPENRNDR 將 Chatbot 訊息視覺化用 OPENRNDR 將 Chatbot 訊息視覺化
用 OPENRNDR 將 Chatbot 訊息視覺化
 
Jenkins-Koji plugin presentation on Python & Ruby devel group @ Brno
Jenkins-Koji plugin presentation on Python & Ruby devel group @ BrnoJenkins-Koji plugin presentation on Python & Ruby devel group @ Brno
Jenkins-Koji plugin presentation on Python & Ruby devel group @ Brno
 

Destaque

AngularJS Security: defend your Single Page Application
AngularJS Security: defend your Single Page Application AngularJS Security: defend your Single Page Application
AngularJS Security: defend your Single Page Application
Carlo Bonamico
 

Destaque (10)

Guide to AngularJS Services - NOVA MEAN August 2014
Guide to AngularJS Services - NOVA MEAN August 2014Guide to AngularJS Services - NOVA MEAN August 2014
Guide to AngularJS Services - NOVA MEAN August 2014
 
Tori.fi - Datalähtöistä kasvua
Tori.fi - Datalähtöistä kasvua Tori.fi - Datalähtöistä kasvua
Tori.fi - Datalähtöistä kasvua
 
Building a Cauldron for Chef to Cook In
Building a Cauldron for Chef to Cook InBuilding a Cauldron for Chef to Cook In
Building a Cauldron for Chef to Cook In
 
NOVA MEAN - Why the M in MEAN is a Significant Contributor to Its Success
NOVA MEAN - Why the M in MEAN is a Significant Contributor to Its SuccessNOVA MEAN - Why the M in MEAN is a Significant Contributor to Its Success
NOVA MEAN - Why the M in MEAN is a Significant Contributor to Its Success
 
Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!
Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!
Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!
 
Dcjq node.js presentation
Dcjq node.js presentationDcjq node.js presentation
Dcjq node.js presentation
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
Google Cloud Platform for the Enterprise
Google Cloud Platform for the EnterpriseGoogle Cloud Platform for the Enterprise
Google Cloud Platform for the Enterprise
 
gRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at SquaregRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at Square
 
AngularJS Security: defend your Single Page Application
AngularJS Security: defend your Single Page Application AngularJS Security: defend your Single Page Application
AngularJS Security: defend your Single Page Application
 

Semelhante a Lessons Learned from Building a REST API on Google App Engine

Connecting to-web-services-on-android-4577
Connecting to-web-services-on-android-4577Connecting to-web-services-on-android-4577
Connecting to-web-services-on-android-4577
sharvari123
 
Best Practices in Widget Development - Examples and Counterexamples
Best Practices in Widget Development  - Examples and CounterexamplesBest Practices in Widget Development  - Examples and Counterexamples
Best Practices in Widget Development - Examples and Counterexamples
ROLE Project
 

Semelhante a Lessons Learned from Building a REST API on Google App Engine (20)

Globus Platform Overview
Globus Platform OverviewGlobus Platform Overview
Globus Platform Overview
 
Gaelyk update - Guillaume Laforge - SpringOne2GX 2011
Gaelyk update - Guillaume Laforge - SpringOne2GX 2011Gaelyk update - Guillaume Laforge - SpringOne2GX 2011
Gaelyk update - Guillaume Laforge - SpringOne2GX 2011
 
Connecting to-web-services-on-android-4577
Connecting to-web-services-on-android-4577Connecting to-web-services-on-android-4577
Connecting to-web-services-on-android-4577
 
Introduction to the Globus Platform (APS Workshop)
Introduction to the Globus Platform (APS Workshop)Introduction to the Globus Platform (APS Workshop)
Introduction to the Globus Platform (APS Workshop)
 
Web Standards Support in WebKit
Web Standards Support in WebKitWeb Standards Support in WebKit
Web Standards Support in WebKit
 
GAE_20100112
GAE_20100112GAE_20100112
GAE_20100112
 
Automating Research Data Flows and an Introduction to the Globus Platform
Automating Research Data Flows and an Introduction to the Globus PlatformAutomating Research Data Flows and an Introduction to the Globus Platform
Automating Research Data Flows and an Introduction to the Globus Platform
 
rest3d Web3D 2014
rest3d Web3D 2014rest3d Web3D 2014
rest3d Web3D 2014
 
Middleware in Golang: InVision's Rye
Middleware in Golang: InVision's RyeMiddleware in Golang: InVision's Rye
Middleware in Golang: InVision's Rye
 
Top 10 HTML5 Features for Oracle Cloud Developers
Top 10 HTML5 Features for Oracle Cloud DevelopersTop 10 HTML5 Features for Oracle Cloud Developers
Top 10 HTML5 Features for Oracle Cloud Developers
 
Automating Research Data Flows and Introduction to the Globus Platform
Automating Research Data Flows and Introduction to the Globus PlatformAutomating Research Data Flows and Introduction to the Globus Platform
Automating Research Data Flows and Introduction to the Globus Platform
 
Building JavaScript
Building JavaScriptBuilding JavaScript
Building JavaScript
 
Introduction to the Globus Platform (GlobusWorld Tour - UMich)
Introduction to the Globus Platform (GlobusWorld Tour - UMich)Introduction to the Globus Platform (GlobusWorld Tour - UMich)
Introduction to the Globus Platform (GlobusWorld Tour - UMich)
 
Best Practices in Widget Development - Examples and Counterexamples
Best Practices in Widget Development  - Examples and CounterexamplesBest Practices in Widget Development  - Examples and Counterexamples
Best Practices in Widget Development - Examples and Counterexamples
 
Google and Beyond: Advanced Search Engine Hacking
Google and Beyond: Advanced Search Engine HackingGoogle and Beyond: Advanced Search Engine Hacking
Google and Beyond: Advanced Search Engine Hacking
 
Google App Engine for Python - Unit01: Basic
Google App Engine for Python - Unit01: BasicGoogle App Engine for Python - Unit01: Basic
Google App Engine for Python - Unit01: Basic
 
Delayed operations with queues for website performance
Delayed operations with queues for website performanceDelayed operations with queues for website performance
Delayed operations with queues for website performance
 
Google App Engine Java, Groovy and Gaelyk
Google App Engine Java, Groovy and GaelykGoogle App Engine Java, Groovy and Gaelyk
Google App Engine Java, Groovy and Gaelyk
 
Accessing Google Cloud APIs
Accessing Google Cloud APIsAccessing Google Cloud APIs
Accessing Google Cloud APIs
 
GlobusWorld 2021 Tutorial: The Globus CLI, Platform and SDK
GlobusWorld 2021 Tutorial: The Globus CLI, Platform and SDKGlobusWorld 2021 Tutorial: The Globus CLI, Platform and SDK
GlobusWorld 2021 Tutorial: The Globus CLI, Platform and SDK
 

Último

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Último (20)

ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide Deck
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 

Lessons Learned from Building a REST API on Google App Engine

  • 1. Lessons Learned from Building a REST API on Google App Engine Jonathan Altman Presentation to GolangDC-October 29, 2015
  • 2. Whitenoise Market Webapp • White Noise by TMSoft (http://www.tmsoft.com/white-noise/) is the leading sleeping app for iOS,Android, Mac, and Windows • Customer wanted a way to: • Allow users to download additional content to the app • Create a vibrant community for users to interact with each other • Scale to the large demand of existing users
  • 3.
  • 5. Project • Build a RESTful API to drive Whitenoise Market’s web front-end • Angular SPA front end, also built as part of the project • User authentication with Google or Facebook account—OAuth2 • Role-based authorization • Implied: customer will use the API from a native mobile client as well • Golang on Google App Engine, leverage their APIs
  • 6. Sample Calls • GET /api/items — get all items • GET /api/item/item_id — get data about the item with id item_id
  • 7. GAE via Golang • Project was approx. 6 person/weeks 2nd 1/2 2014, including front end • Customer specification based on their research • Inherited solid proof of concept app, but no firm API • GAE golang support was still beta, long term support indeterminate • Actual GAE API usage calls: outside the scope of this talk (but see https://cloud.google.com/appengine/docs/go/)
  • 8. Issues • Package management • Routing • REST response formulation/error logging • OAuth2 support for providers other than Google • Authorization • Miscellaneous
  • 9. Package Management • goapp get not go get • Not building an exe locally, packages need to be in source tree uploaded to GAE - feels weird compared to golang philosophy
  • 10. Routing — GAE has choices • Prefix hostname with module — exposing internals • Dispatch file: dispatch.yaml — 10 routing rules max • Roll your own — just start matching URLs in the main dispatch handler in your golang code • or… • and remember: Google Cloud Endpoints were not yet a thing. Probably the way to go today
  • 12. 3rd Party Router: Gorilla mux! • http://www.gorillatoolkit.org/pkg/mux • Gorilla web toolkit has a bunch of other nice parts • Other 3rd party router libraries probably work fine • Parameterization, method control • GAE takes care of a lot of other things Gorilla toolkit provides r.HandleFunc("/api/comments/{sid}",  handleGetComments).Methods("GET")
 r.HandleFunc(“/api/comments/{sid}",  aihttphelper.AuthenticatedEndpoint(HandleAddComment)).Methods("PUT")
  • 13. REST Status/Response Logging • Standard REST success and error responses • gorca — https://github.com/icub3d/gorca • gorca.LogAndMessage: Logs console message and returns short message plus status code • gorca.WriteJSON: succesful responses gorca.LogAndMessage(c,  w,  r,  err,  "error",  "not_authenticated",  http.StatusUnauthorized)   gorca.LogAndMessage(c,  w,  r,  err,  "error",  err.Error(),  http.StatusBadRequest)   gorca.WriteJSON(c,  w,  r,  map[string]interface{}{“status”:  "OK",  "tagAdded":  tagValue})  
  • 14. OAuth2 Support - gomniauth • GAE does OAuth2 authentication…only for Google • gomniauth does OAuth2 authentication for multiple providers, including google (https://github.com/stretchr/gomniauth) • jwt for HTTP Bearer Token — (https://github.com/dgrijalva/jwt-go) • Accepted pull request in gomniauth allows setting http Transport used because the GAE runtime replaces net/http’s DefaultTransport with a context-based one https://github.com/stretchr/gomniauth/pull/23)
  • 15. gomniauth Patch • You have to fetch a Transport with the current requests’ GAE context, and pass that to gomniauth before doing authentication • See https://github.com/jonathana/gomniauth/commit/ 3e2e23995b035e26bbd58a0f56cb2b2d61dbe993 for details/usage
  • 16. Authorization • Separate from authentication. What a user can do, once we know who the user is • Wrapper function shown before: • “Middleware” takes a target function with an extra argument beyond the normal HTTP request handler for the authenticated user information, and returns a normal HTTP handler function that does the authorization check and runs the target function if authorized • Factory functions encapsulated role info, but could pass in ACL data r.HandleFunc(“/api/comments/{sid}",  aihttphelper.AuthenticatedEndpoint(HandleAddComment)).Methods("PUT")
  • 17. Authorization Middlewaretype  AiHandlerFunc  func(appengine.Context,  http.ResponseWriter,  *http.Request,  *aitypes.AIUserInfo)   func  generateAuthenticatedEndpoint(h  AiHandlerFunc,  requiredRoles  aitypes.RoleValue)  http.HandlerFunc  {
   return  func(w  http.ResponseWriter,  r  *http.Request)  {
     c  :=  appengine.NewContext(r)
   
     authUser,  err  :=  AuthenticateRequest(c,  r)
     if  (err  !=  nil)  {
       gorca.LogAndFailed(c,  w,  r,  err)
       return
     }
     //  401  User  not  authenticated     if  (authUser  ==  nil)  {
       http.Error(w,  "",  http.StatusUnauthorized)
       return
     }
     //  403  User  not  authorized  (authenticated,  but  no  permission  to  resource)
     if  (requiredRoles  >  0  &&  !(hasRole(authUser,  requiredRoles))  {
       http.Error(w,  "",  http.StatusForbidden)
       return
     }
   
     //  User  is  authenticated  and  authorized
     h(c,  w,  r,  authUser)
   }
 }   func  AuthenticatedEndpoint(h  WnHandlerFunc)  http.HandlerFunc  {
   return  generateAuthenticatedEndpoint(h,  0)
 }
  • 18. Miscellaneous • Concurrency: ignored as a premature optimization. Issues with urlfetch.Transport led to concern on runtime support/research time • GAE API deprecation: not golang specific, but several APIs in use were deprecated post-project and had to be replaced (blobstore) • GAE appears to be going to more of an a la carte model where existing components are replaced with general GCE equivalents • Google Cloud Endpoints were not available at the time
  • 19. Miscellaneous, cont. • You’ll be playing with the JSON serialization properties. Javascript<- >go naming rules mismatch: nobody wants Javascript properties to begin with capital letters. Also, I tend to prefer map[string]interface{} over defined structs where I can • Using appengine.Context. You will need to, almost everywhere, whether it’s for working with datastore, making outbound http requests, or logging via its .Infof() call