SlideShare a Scribd company logo
How to build SDKs in Go
Lessons from the
Go SDK for Dropbox
Diwaker Gupta
● Infrastructure @
Dropbox
● Metadata Services,
Multihoming, Search,
Messaging, Email,
Notifications, Machine
Learning etc
● Authored Dropbox Go
SDK and dbxcli
● Twitter/Github:
@diwakergupta
users businesses
● Gophercon ‘17 Keynote by @tammybutow:
https://bit.ly/gophercon17dbx
● Dozens of Go services, many with millions of RPS!
● We open source at: https://github.com/dropbox
● We are hiring! dropbox.com/jobs or email me (diwaker@)
Lessons from the Dropbox Go SDK
#1: Use a Code Generator
#1: Use a code generator
● Language-agnostic API definition (DSL, JSON,
YAML, etc), Language-specific generators
● Dropbox Stone (spec + generators)
○ https://github.com/dropbox/stone
● Google
○ JSON Spec https://developers.google.com/discovery/
○ Codegen
https://github.com/google/google-api-go-client/
● AWS Go SDK has a very similar setup
● OpenAPI: https://github.com/OAI/OpenAPI-Specification
#2: Avoid Surprises
#2: Avoid Surprises
● Principle of Least Surprise
● No external dependencies
○ Only standard library imports
● No vendored dependencies
● What you need is what you get
○ Scoped sub-packages for larger APIs (e.g. AWS)
○ Make it `go get` friendly
#3: Make Configuration Simple
#3: Make Configuration Simple
● Don’t use cmdline flags
○ Stdlib limitations
● Environment variables
○ OK, but beware pitfalls
● Use a config struct
○ Same pattern in AWS SDK
● Persistence outside SDK
○ Let applications choose
○ dbxcli load/stores json
configs
// Config contains parameters for
configuring the SDK.
type Config struct {
// OAuth2 access token
Token string
// Enable verbose logging in SDK
Verbose bool
...
// For testing only
Client *http.Client
}
#4: Provide Visibility
#4: Provide Visibility
● Allow verbose logging
● Allow configurable
logging targets
● Limited by stdlib :(
type Config struct {
// Enable verbose logging
Verbose bool
// Optional logging target
Logger *log.Logger
}
// TryLog will, if Verbose is set, log to
// the config's logger or the default logger
// if Config.Logger is nil.
func (c *Config) TryLog(format string, v
...interface{}) {
if !c.Verbose {
return
}
if c.Logger != nil {
c.Logger.Printf(format, v...)
} else {
log.Printf(format, v...)
}
}
#5: Use Go idioms for unsupported types
#5: Unions
Consider (in Stone):
union DeleteError
path_lookup LookupError
path_write WriteError
In JSON (note LookupError):
{
".tag": "path_lookup",
"path_lookup": {
".tag": "malformed_path",
"malformed_path": "/some/path"
}
}
Equivalent struct in Go
type DeleteError struct {
dropbox.Tagged
PathLookup *LookupError `json:"path_lookup"`
PathWrite *WriteError `json:"path_write"`
}
Problem: (de)serialization
func (u *DeleteError) UnmarshalJSON(body []byte)
error {
type wrap struct {
dropbox.Tagged
PathLookup json.RawMessage
PathWrite json.RawMessage
}
var w wrap
switch w.Tag {
case "path_lookup":
err = json.Unmarshal(w.PathLookup,
&u.PathLookup)
...
case "path_write":
err = json.Unmarshal(w.PathWrite,
&u.PathWrite)
...
}
#5: Unions
type DeleteError struct {
dropbox.Tagged
PathLookup *LookupError
`json:"path_lookup,omitempty"`
PathWrite *WriteError
`json:"path_write,omitempty"`
}
{
".tag": "path_lookup",
"path_lookup": {
".tag": "malformed_path",
"malformed_path": "/some/path"
}
}
#5: Inherited Types
In Stone
struct Metadata
// Common fields: Name, Path etc
union
file FileMetadata
folder FolderMetadata
Idiomatic Go: Embedding
type Metadata struct {
// Common fields
}
type FileMetadata struct {
Metadata
// FileMetadata specific fields
}
type FolderMetadata struct {
Metadata
// FolderMetadata specific fields
}
Solution: Use a dummy interface
type IsMetadata interface {
IsMetadata()
}
// Subtypes get this via embedding
func (u *Metadata) IsMetadata() {}
// Use IsMetadata where you need
// the union type
#5: Inherited Types
Problem: Polymorphism
func List(...) []Metadata
Can return FileMetadata or
FolderMetadata
Similar trick as Unions
type metadataUnion struct {
dropbox.Tagged
File *FileMetadata
Folder *FolderMetadata
}
func IsMetadataFromJSON(data []byte) (IsMetadata,
e) {
var t metadataUnion
if err := json.Unmarshal(data, &t); err !=
nil {
return nil, err
}
switch t.Tag {
...
}
}
#5: Inherited Types
Problem: (de)serialization
{
".tag": "file",
"name": "Prime_Numbers.txt",
"id": "id:a4ayc_80_OEAAAAAAAAAXw",
"content_hash": "e3b0c44298fc"
}
OR
{
".tag": "folder",
"name": "math",
"id": "id:a4ayc_80_OEAAAAAAAAAXz",
"path_lower": "/homework/math",
}
#6: Do NOT authenticate
#6: Do NOT authenticate
● Apps authenticate, SDK accepts OAuth Token
● Beware of known OAuth pitfalls
○ Changed OAuth Endpoint from api.dropbox.com to
api.dropboxapi.com
○ App started failing with oauth2: cannot fetch token:
400 Bad Request
○ Gem from oauth2/internal/token.go
○ func RegisterBrokenAuthHeaderProvider(tokenURL string)
○ Google, Stripe and yes, Dropbox are “broken”
● More information:
○ On debugging OAuth2 in #golang
#7: Auto Generate Tests
#7: Auto Generate Tests
● Tests should be
comprehensive and
up-to-date
● Dropbox SDK is NOT a
good example!
● Model after AWS SDK
○ Example input/output
defined in JSON
○ Tests are auto-generated
● Not a panacea, still
need to write tests!
○ Especially negative tests
#8: Handle errors the Go way
#8: Handle errors the Go way
Dropbox SDK
res, err := dbx.ListFolder(arg)
if err != nil {
switch e := err.(type) {
case files.ListFolderAPIError:
...
AWS SDK
output, err := s3manage.Upload(...)
if err != nil {
if reqerr, ok := err.(RequestFailure);
ok {
...
● Have SDK errors implement the `error` interface
● Use type assertions to extract errors
● Good packages exist for combining / unrolling errors --
wish stdlib had more support!
Lessons Recap
1. Use a Code Generator
2. Avoid Surprises
3. Make Configuration Simple
4. Provide Visibility
5. Use Go Idioms for Unsupported Types
6. Do Not Authenticate
7. Auto Generate Tests
8. Handle Errors the Go Way
Where to get it?
● SDK:https://github.com/dropbox/dropbox-sdk-go-unofficial
● dbxcli: https://github.com/dropbox/dbxcli/
○ Command line tool for Dropbox
○ Pre-compiled binaries for Windows, Mac, Linux, ARM
○ Useful for end users as well as team administrators
● Support for Dropbox Paper coming soon!
○ https://www.dropbox.com/paper
How to build SDKs in Go
How to build SDKs in Go

More Related Content

What's hot

Implementing Domain Events with Kafka
Implementing Domain Events with KafkaImplementing Domain Events with Kafka
Implementing Domain Events with Kafka
Andrei Rugina
 
Easy Microservices with JHipster - Devoxx BE 2017
Easy Microservices with JHipster - Devoxx BE 2017Easy Microservices with JHipster - Devoxx BE 2017
Easy Microservices with JHipster - Devoxx BE 2017
Deepu K Sasidharan
 
Domain Driven Design
Domain Driven Design Domain Driven Design
Domain Driven Design
Araf Karsh Hamid
 
SQL Transactions - What they are good for and how they work
SQL Transactions - What they are good for and how they workSQL Transactions - What they are good for and how they work
SQL Transactions - What they are good for and how they work
Markus Winand
 
codecentric AG: CQRS and Event Sourcing Applications with Cassandra
codecentric AG: CQRS and Event Sourcing Applications with Cassandracodecentric AG: CQRS and Event Sourcing Applications with Cassandra
codecentric AG: CQRS and Event Sourcing Applications with Cassandra
DataStax Academy
 
MongodB Internals
MongodB InternalsMongodB Internals
MongodB Internals
Norberto Leite
 
Accessibility pitch-deck
Accessibility pitch-deckAccessibility pitch-deck
Accessibility pitch-deck
Karthikeyan Dhanasekaran CUA
 
JSON-LD for RESTful services
JSON-LD for RESTful servicesJSON-LD for RESTful services
JSON-LD for RESTful services
Markus Lanthaler
 
Jitney, Kafka at Airbnb
Jitney, Kafka at AirbnbJitney, Kafka at Airbnb
Jitney, Kafka at Airbnb
alexismidon
 
Property graph vs. RDF Triplestore comparison in 2020
Property graph vs. RDF Triplestore comparison in 2020Property graph vs. RDF Triplestore comparison in 2020
Property graph vs. RDF Triplestore comparison in 2020
Ontotext
 
Log analytics with ELK stack
Log analytics with ELK stackLog analytics with ELK stack
Log analytics with ELK stack
AWS User Group Bengaluru
 
Three Pillars, Zero Answers: Rethinking Observability
Three Pillars, Zero Answers: Rethinking ObservabilityThree Pillars, Zero Answers: Rethinking Observability
Three Pillars, Zero Answers: Rethinking Observability
DevOps.com
 
Optimizing Hive Queries
Optimizing Hive QueriesOptimizing Hive Queries
Optimizing Hive Queries
DataWorks Summit
 
DDD Strategic Design - Context Maps - Paulo Clavijo - April 2018
DDD Strategic Design - Context Maps - Paulo Clavijo - April 2018DDD Strategic Design - Context Maps - Paulo Clavijo - April 2018
DDD Strategic Design - Context Maps - Paulo Clavijo - April 2018
Paulo Clavijo
 
Building mobile apps on aws
Building mobile apps on awsBuilding mobile apps on aws
Building mobile apps on aws
Amazon Web Services
 
From capabilities to services modelling for business-it alignment v.2
From capabilities to services   modelling for business-it alignment v.2From capabilities to services   modelling for business-it alignment v.2
From capabilities to services modelling for business-it alignment v.2
Trond Hjorteland
 
Aggregated queries with Druid on terrabytes and petabytes of data
Aggregated queries with Druid on terrabytes and petabytes of dataAggregated queries with Druid on terrabytes and petabytes of data
Aggregated queries with Druid on terrabytes and petabytes of data
Rostislav Pashuto
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
Aniruddh Bhilvare
 
Exchange and Consumption of Huge RDF Data
Exchange and Consumption of Huge RDF DataExchange and Consumption of Huge RDF Data
Exchange and Consumption of Huge RDF Data
Mario Arias
 

What's hot (20)

Implementing Domain Events with Kafka
Implementing Domain Events with KafkaImplementing Domain Events with Kafka
Implementing Domain Events with Kafka
 
Easy Microservices with JHipster - Devoxx BE 2017
Easy Microservices with JHipster - Devoxx BE 2017Easy Microservices with JHipster - Devoxx BE 2017
Easy Microservices with JHipster - Devoxx BE 2017
 
Domain Driven Design
Domain Driven Design Domain Driven Design
Domain Driven Design
 
Domain Event - The Hidden Gem of DDD
Domain Event - The Hidden Gem of DDDDomain Event - The Hidden Gem of DDD
Domain Event - The Hidden Gem of DDD
 
SQL Transactions - What they are good for and how they work
SQL Transactions - What they are good for and how they workSQL Transactions - What they are good for and how they work
SQL Transactions - What they are good for and how they work
 
codecentric AG: CQRS and Event Sourcing Applications with Cassandra
codecentric AG: CQRS and Event Sourcing Applications with Cassandracodecentric AG: CQRS and Event Sourcing Applications with Cassandra
codecentric AG: CQRS and Event Sourcing Applications with Cassandra
 
MongodB Internals
MongodB InternalsMongodB Internals
MongodB Internals
 
Accessibility pitch-deck
Accessibility pitch-deckAccessibility pitch-deck
Accessibility pitch-deck
 
JSON-LD for RESTful services
JSON-LD for RESTful servicesJSON-LD for RESTful services
JSON-LD for RESTful services
 
Jitney, Kafka at Airbnb
Jitney, Kafka at AirbnbJitney, Kafka at Airbnb
Jitney, Kafka at Airbnb
 
Property graph vs. RDF Triplestore comparison in 2020
Property graph vs. RDF Triplestore comparison in 2020Property graph vs. RDF Triplestore comparison in 2020
Property graph vs. RDF Triplestore comparison in 2020
 
Log analytics with ELK stack
Log analytics with ELK stackLog analytics with ELK stack
Log analytics with ELK stack
 
Three Pillars, Zero Answers: Rethinking Observability
Three Pillars, Zero Answers: Rethinking ObservabilityThree Pillars, Zero Answers: Rethinking Observability
Three Pillars, Zero Answers: Rethinking Observability
 
Optimizing Hive Queries
Optimizing Hive QueriesOptimizing Hive Queries
Optimizing Hive Queries
 
DDD Strategic Design - Context Maps - Paulo Clavijo - April 2018
DDD Strategic Design - Context Maps - Paulo Clavijo - April 2018DDD Strategic Design - Context Maps - Paulo Clavijo - April 2018
DDD Strategic Design - Context Maps - Paulo Clavijo - April 2018
 
Building mobile apps on aws
Building mobile apps on awsBuilding mobile apps on aws
Building mobile apps on aws
 
From capabilities to services modelling for business-it alignment v.2
From capabilities to services   modelling for business-it alignment v.2From capabilities to services   modelling for business-it alignment v.2
From capabilities to services modelling for business-it alignment v.2
 
Aggregated queries with Druid on terrabytes and petabytes of data
Aggregated queries with Druid on terrabytes and petabytes of dataAggregated queries with Druid on terrabytes and petabytes of data
Aggregated queries with Druid on terrabytes and petabytes of data
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
Exchange and Consumption of Huge RDF Data
Exchange and Consumption of Huge RDF DataExchange and Consumption of Huge RDF Data
Exchange and Consumption of Huge RDF Data
 

Similar to How to build SDKs in Go

Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
Rodolfo Carvalho
 
Grails Introduction - IJTC 2007
Grails Introduction - IJTC 2007Grails Introduction - IJTC 2007
Grails Introduction - IJTC 2007
Guillaume Laforge
 
"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson
GWTcon
 
Getting started with go - Florin Patan - Codemotion Milan 2016
Getting started with go - Florin Patan - Codemotion Milan 2016Getting started with go - Florin Patan - Codemotion Milan 2016
Getting started with go - Florin Patan - Codemotion Milan 2016
Codemotion
 
Grooscript greach
Grooscript greachGrooscript greach
Grooscript greach
Jorge Franco Leza
 
dojo.Patterns
dojo.Patternsdojo.Patterns
dojo.Patterns
Peter Higgins
 
Mobile Apps by Pure Go with Reverse Binding
Mobile Apps by Pure Go with Reverse BindingMobile Apps by Pure Go with Reverse Binding
Mobile Apps by Pure Go with Reverse Binding
Takuya Ueda
 
Building Dojo in the Cloud
Building Dojo in the CloudBuilding Dojo in the Cloud
Building Dojo in the Cloud
James Thomas
 
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...Guillaume Laforge
 
Build Great Networked APIs with Swift, OpenAPI, and gRPC
Build Great Networked APIs with Swift, OpenAPI, and gRPCBuild Great Networked APIs with Swift, OpenAPI, and gRPC
Build Great Networked APIs with Swift, OpenAPI, and gRPC
Tim Burks
 
Grooscript gr8conf 2015
Grooscript gr8conf 2015Grooscript gr8conf 2015
Grooscript gr8conf 2015
Jorge Franco Leza
 
Go, meet Lua
Go, meet LuaGo, meet Lua
Go, meet Lua
Andre Burgaud
 
Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)
Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)
Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)
Igalia
 
Daniel Steigerwald: EsteJS - javascriptové aplikace robusně, modulárně a komf...
Daniel Steigerwald: EsteJS - javascriptové aplikace robusně, modulárně a komf...Daniel Steigerwald: EsteJS - javascriptové aplikace robusně, modulárně a komf...
Daniel Steigerwald: EsteJS - javascriptové aplikace robusně, modulárně a komf...
Develcz
 
Little Did He Know ...
Little Did He Know ...Little Did He Know ...
Little Did He Know ...
Burt Beckwith
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
Leo Hernandez
 
Cape Cod Web Technology Meetup - 3
Cape Cod Web Technology Meetup - 3Cape Cod Web Technology Meetup - 3
Cape Cod Web Technology Meetup - 3
Asher Martin
 
PHP BASIC PRESENTATION
PHP BASIC PRESENTATIONPHP BASIC PRESENTATION
PHP BASIC PRESENTATION
krutitrivedi
 
Golang introduction
Golang introductionGolang introduction
Golang introduction
DineshDinesh131
 
SF Grails - Ratpack - Compact Groovy Webapps - James Williams
SF Grails - Ratpack - Compact Groovy Webapps - James WilliamsSF Grails - Ratpack - Compact Groovy Webapps - James Williams
SF Grails - Ratpack - Compact Groovy Webapps - James Williams
Philip Stehlik
 

Similar to How to build SDKs in Go (20)

Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
 
Grails Introduction - IJTC 2007
Grails Introduction - IJTC 2007Grails Introduction - IJTC 2007
Grails Introduction - IJTC 2007
 
"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson
 
Getting started with go - Florin Patan - Codemotion Milan 2016
Getting started with go - Florin Patan - Codemotion Milan 2016Getting started with go - Florin Patan - Codemotion Milan 2016
Getting started with go - Florin Patan - Codemotion Milan 2016
 
Grooscript greach
Grooscript greachGrooscript greach
Grooscript greach
 
dojo.Patterns
dojo.Patternsdojo.Patterns
dojo.Patterns
 
Mobile Apps by Pure Go with Reverse Binding
Mobile Apps by Pure Go with Reverse BindingMobile Apps by Pure Go with Reverse Binding
Mobile Apps by Pure Go with Reverse Binding
 
Building Dojo in the Cloud
Building Dojo in the CloudBuilding Dojo in the Cloud
Building Dojo in the Cloud
 
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
 
Build Great Networked APIs with Swift, OpenAPI, and gRPC
Build Great Networked APIs with Swift, OpenAPI, and gRPCBuild Great Networked APIs with Swift, OpenAPI, and gRPC
Build Great Networked APIs with Swift, OpenAPI, and gRPC
 
Grooscript gr8conf 2015
Grooscript gr8conf 2015Grooscript gr8conf 2015
Grooscript gr8conf 2015
 
Go, meet Lua
Go, meet LuaGo, meet Lua
Go, meet Lua
 
Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)
Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)
Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)
 
Daniel Steigerwald: EsteJS - javascriptové aplikace robusně, modulárně a komf...
Daniel Steigerwald: EsteJS - javascriptové aplikace robusně, modulárně a komf...Daniel Steigerwald: EsteJS - javascriptové aplikace robusně, modulárně a komf...
Daniel Steigerwald: EsteJS - javascriptové aplikace robusně, modulárně a komf...
 
Little Did He Know ...
Little Did He Know ...Little Did He Know ...
Little Did He Know ...
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
Cape Cod Web Technology Meetup - 3
Cape Cod Web Technology Meetup - 3Cape Cod Web Technology Meetup - 3
Cape Cod Web Technology Meetup - 3
 
PHP BASIC PRESENTATION
PHP BASIC PRESENTATIONPHP BASIC PRESENTATION
PHP BASIC PRESENTATION
 
Golang introduction
Golang introductionGolang introduction
Golang introduction
 
SF Grails - Ratpack - Compact Groovy Webapps - James Williams
SF Grails - Ratpack - Compact Groovy Webapps - James WilliamsSF Grails - Ratpack - Compact Groovy Webapps - James Williams
SF Grails - Ratpack - Compact Groovy Webapps - James Williams
 

Recently uploaded

BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 

Recently uploaded (20)

BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 

How to build SDKs in Go

  • 1. How to build SDKs in Go Lessons from the Go SDK for Dropbox
  • 2. Diwaker Gupta ● Infrastructure @ Dropbox ● Metadata Services, Multihoming, Search, Messaging, Email, Notifications, Machine Learning etc ● Authored Dropbox Go SDK and dbxcli ● Twitter/Github: @diwakergupta
  • 4. ● Gophercon ‘17 Keynote by @tammybutow: https://bit.ly/gophercon17dbx ● Dozens of Go services, many with millions of RPS! ● We open source at: https://github.com/dropbox ● We are hiring! dropbox.com/jobs or email me (diwaker@)
  • 5. Lessons from the Dropbox Go SDK
  • 6. #1: Use a Code Generator
  • 7. #1: Use a code generator ● Language-agnostic API definition (DSL, JSON, YAML, etc), Language-specific generators ● Dropbox Stone (spec + generators) ○ https://github.com/dropbox/stone ● Google ○ JSON Spec https://developers.google.com/discovery/ ○ Codegen https://github.com/google/google-api-go-client/ ● AWS Go SDK has a very similar setup ● OpenAPI: https://github.com/OAI/OpenAPI-Specification
  • 9. #2: Avoid Surprises ● Principle of Least Surprise ● No external dependencies ○ Only standard library imports ● No vendored dependencies ● What you need is what you get ○ Scoped sub-packages for larger APIs (e.g. AWS) ○ Make it `go get` friendly
  • 11. #3: Make Configuration Simple ● Don’t use cmdline flags ○ Stdlib limitations ● Environment variables ○ OK, but beware pitfalls ● Use a config struct ○ Same pattern in AWS SDK ● Persistence outside SDK ○ Let applications choose ○ dbxcli load/stores json configs // Config contains parameters for configuring the SDK. type Config struct { // OAuth2 access token Token string // Enable verbose logging in SDK Verbose bool ... // For testing only Client *http.Client }
  • 13. #4: Provide Visibility ● Allow verbose logging ● Allow configurable logging targets ● Limited by stdlib :( type Config struct { // Enable verbose logging Verbose bool // Optional logging target Logger *log.Logger } // TryLog will, if Verbose is set, log to // the config's logger or the default logger // if Config.Logger is nil. func (c *Config) TryLog(format string, v ...interface{}) { if !c.Verbose { return } if c.Logger != nil { c.Logger.Printf(format, v...) } else { log.Printf(format, v...) } }
  • 14. #5: Use Go idioms for unsupported types
  • 15. #5: Unions Consider (in Stone): union DeleteError path_lookup LookupError path_write WriteError In JSON (note LookupError): { ".tag": "path_lookup", "path_lookup": { ".tag": "malformed_path", "malformed_path": "/some/path" } } Equivalent struct in Go type DeleteError struct { dropbox.Tagged PathLookup *LookupError `json:"path_lookup"` PathWrite *WriteError `json:"path_write"` } Problem: (de)serialization
  • 16. func (u *DeleteError) UnmarshalJSON(body []byte) error { type wrap struct { dropbox.Tagged PathLookup json.RawMessage PathWrite json.RawMessage } var w wrap switch w.Tag { case "path_lookup": err = json.Unmarshal(w.PathLookup, &u.PathLookup) ... case "path_write": err = json.Unmarshal(w.PathWrite, &u.PathWrite) ... } #5: Unions type DeleteError struct { dropbox.Tagged PathLookup *LookupError `json:"path_lookup,omitempty"` PathWrite *WriteError `json:"path_write,omitempty"` } { ".tag": "path_lookup", "path_lookup": { ".tag": "malformed_path", "malformed_path": "/some/path" } }
  • 17. #5: Inherited Types In Stone struct Metadata // Common fields: Name, Path etc union file FileMetadata folder FolderMetadata Idiomatic Go: Embedding type Metadata struct { // Common fields } type FileMetadata struct { Metadata // FileMetadata specific fields } type FolderMetadata struct { Metadata // FolderMetadata specific fields }
  • 18. Solution: Use a dummy interface type IsMetadata interface { IsMetadata() } // Subtypes get this via embedding func (u *Metadata) IsMetadata() {} // Use IsMetadata where you need // the union type #5: Inherited Types Problem: Polymorphism func List(...) []Metadata Can return FileMetadata or FolderMetadata
  • 19. Similar trick as Unions type metadataUnion struct { dropbox.Tagged File *FileMetadata Folder *FolderMetadata } func IsMetadataFromJSON(data []byte) (IsMetadata, e) { var t metadataUnion if err := json.Unmarshal(data, &t); err != nil { return nil, err } switch t.Tag { ... } } #5: Inherited Types Problem: (de)serialization { ".tag": "file", "name": "Prime_Numbers.txt", "id": "id:a4ayc_80_OEAAAAAAAAAXw", "content_hash": "e3b0c44298fc" } OR { ".tag": "folder", "name": "math", "id": "id:a4ayc_80_OEAAAAAAAAAXz", "path_lower": "/homework/math", }
  • 20. #6: Do NOT authenticate
  • 21. #6: Do NOT authenticate ● Apps authenticate, SDK accepts OAuth Token ● Beware of known OAuth pitfalls ○ Changed OAuth Endpoint from api.dropbox.com to api.dropboxapi.com ○ App started failing with oauth2: cannot fetch token: 400 Bad Request ○ Gem from oauth2/internal/token.go ○ func RegisterBrokenAuthHeaderProvider(tokenURL string) ○ Google, Stripe and yes, Dropbox are “broken” ● More information: ○ On debugging OAuth2 in #golang
  • 23. #7: Auto Generate Tests ● Tests should be comprehensive and up-to-date ● Dropbox SDK is NOT a good example! ● Model after AWS SDK ○ Example input/output defined in JSON ○ Tests are auto-generated ● Not a panacea, still need to write tests! ○ Especially negative tests
  • 24. #8: Handle errors the Go way
  • 25. #8: Handle errors the Go way Dropbox SDK res, err := dbx.ListFolder(arg) if err != nil { switch e := err.(type) { case files.ListFolderAPIError: ... AWS SDK output, err := s3manage.Upload(...) if err != nil { if reqerr, ok := err.(RequestFailure); ok { ... ● Have SDK errors implement the `error` interface ● Use type assertions to extract errors ● Good packages exist for combining / unrolling errors -- wish stdlib had more support!
  • 26. Lessons Recap 1. Use a Code Generator 2. Avoid Surprises 3. Make Configuration Simple 4. Provide Visibility 5. Use Go Idioms for Unsupported Types 6. Do Not Authenticate 7. Auto Generate Tests 8. Handle Errors the Go Way
  • 27. Where to get it? ● SDK:https://github.com/dropbox/dropbox-sdk-go-unofficial ● dbxcli: https://github.com/dropbox/dbxcli/ ○ Command line tool for Dropbox ○ Pre-compiled binaries for Windows, Mac, Linux, ARM ○ Useful for end users as well as team administrators ● Support for Dropbox Paper coming soon! ○ https://www.dropbox.com/paper