SlideShare ist ein Scribd-Unternehmen logo
1 von 44
Downloaden Sie, um offline zu lesen
RESTful Web Applications
with Google Go
Frank Müller
Oldenburg / Germany
Released Summer 1965
Software Engineer
Author
!
mue@tideland.biz
blog.tideland.biz
@themue
github.com/tideland
Goals
• Usage of HTTP / HTTPS

• Multiplexing based on path containing functional
domain, resource, and possible resource id

• List of multiple handles to support generic tasks like
authentication and authorization

• Mapping of HTTP methods to CRUD operations

• Major data is JSON, but also XML and templates
Google Go
Go HTTP Package
• Simple

• Types implementing http.Handler interface or
functions with a defined signature for handling

• Integrated server able to handle HTTP and HTTPS

• Not very convenient
Go HTTP Package - Handler
type MyHandler struct{}
!
// Implementing http.Handler interface.
func (mh *MyHandler) ServeHTTP(
	 w http.ResponseWriter,
	 r *http.Request) {
	 w.Header().Set(”Content-Type”, ”text/plain”)
	 w.WriteHeader(http.StatusOK)
	 fmt.Fprintln(w, ”Hello, Go User Group!”)
}
Go HTTP Package - Main
!
func main() {
	 // Register handler for path.
	 http.Handle(”/myHandler”, &MyHandler{})
!
	 // Start server on port 8080.
	 log.Fatal(http.ListenAndServe(”:8080”, nil))
}
❝Simple tasks can be done using the
standard library, but own powerful
packages are easy to create.
–Gopher
RESTful Web Multiplexer
Multiplexer
• Go default uses a prefix based pattern

• Our RWM maps based on domain and resource

• Request and response wrapped into convenient
context

• Fallback to a default handler
Multiplexer - Type
// RESTfulWebMultiplexer is our own multiplexer.
type RESTfulWebMultiplexer struct {
	 mapping domains
	 …
}
!
// AddHandler adds a handler based on domain and resource.
func (mux * RESTfulWebMultiplexer) AddHandler(
	 domain, resource string,
	 h ResourceHandler) error {
	 …
}
Multiplexer - Interface Method
// ServeHTTP implements the handler interface.
func (mux * RESTfulWebMultiplexer) ServeHTTP(
	 w http.ResponseWriter,
	 r *http.Request) {
	 ctx := newContext(mux, w, r)
	 if err := mux.mapping.handle(ctx); err != nil {
	 	 …
	 }
}
Multiplexer - Main
!
func main() {
	 // Create multiplexer and add handlers.
	 mux := NewRESTfulWebMultiplexer()
!
	 mux.AddHandler(”content”, ”blog”, NewBlogHandler())
	 …
!
	 // Start server with our multiplexer on port 8080.
	 log.Fatal(http.ListenAndServe(”:8080”, mux))
}
❝Own multiplexers make HTTP server
more flexible.
–Gopher
Multiplexer - Domains
// domains maps domains to their resources.
type domains map[string]resources
!
// handle retrieves the resources for the context domain and
// lets them handle the context.
func (d domains) handle(
	 ctx *RequestContext) error {
	 resources, ok := d[ctx.Domain]
	 if !ok {
	 	 resources = d[ctx.Mux.DefaultDomain()]
	 }
	 // Continue handling.
	 return resources.handle(ctx)
}
Multiplexer - Resources
// resources maps resources to their handler lists.
type resources map[string]handlers
!
// handle retrieves the handlers for the context resource and lets
// them handle the context.
func (r resources) handle(
	 ctx *RequestContext) error {
	 handlers, ok := r[ctx.Resource]
	 if !ok {
	 	 handlers = r[ctx.Mux.DefaultResource(ctx.Domain)]
	 }
	 // Continue handling.
	 return handlers.handle(ctx)
}
Multiplexer - Handlers
// handlers chains all handlers for one resource.
type handlers []ResourceHandler
!
// handle lets all handlers handle the context.
func (h handlers) handle(
	 ctx *RequestContext) error {
	 for _, handler := range h {
	 	 ok, err := ctx.Mux.dispatch(ctx, handler)
	 	 if err != nil { return err }
	 	 // Handler tells to stop, but w/o error.
	 	 if !ok { return nil }
	 }
	 return nil
}
❝Use my simple type system for small
types with useful methods.
–Gopher
Handle your resources
Resource Handler
• Basic interface for initialization and read operation

• Additional interfaces for create, update, and delete
operations

• Dispatcher to map HTTP methods
Resource Handler - Base Interface
// ResourceHandler defines the base interface. It handles the
// HTTP GET method with Read().
type ResourceHandler interface {
	 // Init is called after registration of the handler.
	 Init(domain, resource string) error
!
	 // Read is called if the HTTP method is GET.
	 Read(ctx *Context) (bool, error)
}
Resource Handler - Create Interface
// CreateResourceHandler defines the interface to additionally
// handle the HTTP POST with Create().
type CreateResourceHandler interface {
	 // Create is called if the HTTP method is POST.
	 Create(ctx *Context) (bool, error)
}
Resource Handler - Dispatch
// dispatch maps HTTP methods to handler function calls.
func (mux *RESTfulWebMultiplexer) dispatch(
	 ctx *Context, h ResourceHandler) (bool, error) {
	 switch ctx.Request.Method {
	 case ”GET”:
	 	 return h.Read(ctx)
	 case ”POST”:
	 	 if ch, ok := h.(CreateResourceHandler); ok {
	 	 	 return ch.Create(ctx)
	 	 }
	 	 return false, errors.New(”handler cannot process POST”)
	 case …
	 }
	 return false, errors.New(”invalid HTTP method”)
}
❝Small interfaces and type assertions
are a powerful combination.
–Gopher
See the context
Context
• Simple wrapper for request and response

• Provides information about domain, resource and id

• Also provides information about stuff like accepted
content types and languages

• Allows simpler reading and writing of JSON etc.
Context - Type
// Context encapsulates all needed data for handling a request.
type Context struct {
	 Mux	 	 	 	 	 	 	 	 	 *RESTfulWebMultiplexer
	 Writer	 	 	 	 	 	 	 	 http.ResponseWriter
	 Request	 	 	 	 	 	 	 	 *http.Request
	 Domain, Resource, ResourceId	 string
}
!
// newContext creates a new context and parses the URL path.
func newContext(
	 mux	 *RESTfulWebMultiplexer,
	 w	 	 http.ResponseWriter,
	 r	 	 *http.Request) *Context { … }
Context - Simple Request Analysis
// accepts checks if the requestor accepts a content type.
func (ctx *Context) accepts(ct string) bool {
	 accept := ctx.Request.Header.Get(”Accept”)
	 return strings.Contains(accept, ct)
}
!
// AcceptsJSON checks if the requestor accepts JSON as
// a content type.
func (ctx *Context) AcceptsJSON() bool {	
	 return ctx.accepts(”application/json”)
}
Context - Typical Operations
// Redirect to a domain, resource and resource id (optional).
func (ctx *Context) Redirect(
	 domain, resource, resourceId string) {
	 url := ctx.Mux.BasePath() + domain + ”/” + resource
	 if resourceId != ”” {
	 	 url += ”/” + resourceId
	 }
	 ctx.Writer.Header().Set(”Location”, url)
	 ctx.Writer.WriteHeader(http.StatusMovedPermanently)
}
❝Public fields are not evil as long as
the data is not shared.
–Gopher
JSON Marshaling
• Go likes JSON

• Really! (scnr)

• Automatically, controlled, and manually
JSON - Standard
// Public fields will be marshaled.
type Demo struct {
	 FieldA	 string
	 FieldB	 int
	 FieldC		 *OtherStruct
	 fieldX		 bool	 	 	 	 // No, you won’t see me.
}
!
demo := &demo{ … }
!
// b contains the marshaled demo struct as []byte.
b, err := json.Marshal(demo)
JSON - Controlled
// Control with field tags.
type AnotherDemo struct {
	 FieldA	 string		 `json:”-”`	 	 	 	 // Ignore.
	 FieldB	 int		 	 `json:”OtherName”`	 // Change name.
	 FieldC		 float64	 `json:”,string”`	 	 // As string.	 	
	 FieldD	 bool	 	 `json:”,omitempty”`	// Ignore if empty.
	 FieldE		 string		 	 	 	 	 	 	 	 // As usual.
	 fieldX		 int		 	 	 	 	 	 	 	 	 // Still ignored.
}
JSON - Manually
// User has to care for it.
type StillADemo struct {
	 fieldA	string
	 fieldB	int
}
!
// MarshalJSON implements the Marshaler interface.
func (d *StillADemo) MarshalJSON() ([]byte, error) {
	 format := `{”First”: %q, ”Second”: %d}`
	 json := fmt.Sprintf(format, d.fieldA, d.fieldB)
	 return []byte(json), nil
}
JSON - Integrate in Context
func (ctx *Context) RespondJSON(
	 data interface{}, html bool) error {
	 b, err := json.Marshal(data)
	 if err != nil {
	 	 return fmt.Errorf(”cannot respond JSON: %v”, err)
	 }
	 if html {
	 	 var buf bytes.Buffer
	 	 json.HTMLEscape(&buf, b)
	 	 b = buf.Bytes()
	 }
	 ctx.Writer.Header().Set(”Content-Type”, ”application/json”)
	 _, err = ctx.Writer.Write(b)
	 return err
}
❝My standard library provides powerful
encoding packages, also for XML,
CSV, ASN.1, etc.
–Gopher
Scenario
Tags by Interest
Browser
Stat
Handler
Content
Handler
Tag
Handler
Content
Backend
Stat
Backend
DB
GET /content/page/4711
GET /content/tags/interest Goroutines
Async Update
Page Request

gets HTML
JS Request

gets JSON
Stat Handler
func (h *StatHandler) Read(ctx *rwm.Context) (bool, error) {
	 if ctx.ResourceId != ”” {
	 	 // Backend handles update in background.
	 	 statBackend.UpdatePage(ctx.ResourceId)
	 }
	 return true, nil
}
Content Handler
func (h *ContentHandler) Read(
	 ctx *rwm.Context) (bool, error) {
	 var page *Page
	 if ctx.ResourceId != ”” {
	 	 page = contentBackend.Page(ctx.ResourceId)	 	
	 } else {
	 	 page = contentBackend.Index()
	 }
	 if err := ctx.RespondTemplate(h.template, page); err != nil {
	 	 return false, err
	 }
	 return true, nil
}
Tag Handler
func (h *StatHandler) Read(ctx *rwm.Context) (bool, error) {
	 var err error
	 switch ctx.ResourceId {
	 case ”interest”:
	 	 tags := statBackend.TagsByInterest()
	 	 if ctx.AcceptsJSON() {
	 	 	 err = ctx.RespondJSON(tags, true)
	 	 } else if ctx.AcceptsXML() {
	 	 	 err = ctx.RespondXML(tags)
	 	 }
	 case …
	 }
	 …	
}
❝Enjoy Go, it’s lightweight, simple and
very productive.
–Gopher
❝ Zitat hier eingeben.
–Christian BauerImages
123RF

iStockphoto

Own Sources

Weitere ähnliche Inhalte

Was ist angesagt?

The Aggregation Framework
The Aggregation FrameworkThe Aggregation Framework
The Aggregation FrameworkMongoDB
 
OpenStack Log Mining
OpenStack Log MiningOpenStack Log Mining
OpenStack Log MiningJohn Stanford
 
RESTful Web Services with Jersey
RESTful Web Services with JerseyRESTful Web Services with Jersey
RESTful Web Services with JerseyScott Leberknight
 
Building Go Web Apps
Building Go Web AppsBuilding Go Web Apps
Building Go Web AppsMark
 
Webinar: Exploring the Aggregation Framework
Webinar: Exploring the Aggregation FrameworkWebinar: Exploring the Aggregation Framework
Webinar: Exploring the Aggregation FrameworkMongoDB
 
Exported resources design patterns
Exported resources design patternsExported resources design patterns
Exported resources design patternsYevgeny Trachtinov
 
Agg framework selectgroup feb2015 v2
Agg framework selectgroup feb2015 v2Agg framework selectgroup feb2015 v2
Agg framework selectgroup feb2015 v2MongoDB
 
Spark Structured Streaming
Spark Structured Streaming Spark Structured Streaming
Spark Structured Streaming Revin Chalil
 
MongoDB Aggregation Framework
MongoDB Aggregation FrameworkMongoDB Aggregation Framework
MongoDB Aggregation FrameworkTyler Brock
 
So various polymorphism in Scala
So various polymorphism in ScalaSo various polymorphism in Scala
So various polymorphism in Scalab0ris_1
 
The Aggregation Framework
The Aggregation FrameworkThe Aggregation Framework
The Aggregation FrameworkMongoDB
 
MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...
MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...
MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...MongoDB
 
MongoDB Europe 2016 - Graph Operations with MongoDB
MongoDB Europe 2016 - Graph Operations with MongoDBMongoDB Europe 2016 - Graph Operations with MongoDB
MongoDB Europe 2016 - Graph Operations with MongoDBMongoDB
 
Analytics with MongoDB Aggregation Framework and Hadoop Connector
Analytics with MongoDB Aggregation Framework and Hadoop ConnectorAnalytics with MongoDB Aggregation Framework and Hadoop Connector
Analytics with MongoDB Aggregation Framework and Hadoop ConnectorHenrik Ingo
 
Data Processing and Aggregation with MongoDB
Data Processing and Aggregation with MongoDB Data Processing and Aggregation with MongoDB
Data Processing and Aggregation with MongoDB MongoDB
 

Was ist angesagt? (19)

The Aggregation Framework
The Aggregation FrameworkThe Aggregation Framework
The Aggregation Framework
 
I os 13
I os 13I os 13
I os 13
 
OpenStack Log Mining
OpenStack Log MiningOpenStack Log Mining
OpenStack Log Mining
 
RESTful Web Services with Jersey
RESTful Web Services with JerseyRESTful Web Services with Jersey
RESTful Web Services with Jersey
 
Building Go Web Apps
Building Go Web AppsBuilding Go Web Apps
Building Go Web Apps
 
Webinar: Exploring the Aggregation Framework
Webinar: Exploring the Aggregation FrameworkWebinar: Exploring the Aggregation Framework
Webinar: Exploring the Aggregation Framework
 
Exported resources design patterns
Exported resources design patternsExported resources design patterns
Exported resources design patterns
 
C++
C++C++
C++
 
Agg framework selectgroup feb2015 v2
Agg framework selectgroup feb2015 v2Agg framework selectgroup feb2015 v2
Agg framework selectgroup feb2015 v2
 
Spark Structured Streaming
Spark Structured Streaming Spark Structured Streaming
Spark Structured Streaming
 
MongoDB Aggregation Framework
MongoDB Aggregation FrameworkMongoDB Aggregation Framework
MongoDB Aggregation Framework
 
So various polymorphism in Scala
So various polymorphism in ScalaSo various polymorphism in Scala
So various polymorphism in Scala
 
The Aggregation Framework
The Aggregation FrameworkThe Aggregation Framework
The Aggregation Framework
 
MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...
MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...
MongoDB Analytics: Learn Aggregation by Example - Exploratory Analytics and V...
 
Lec 7
Lec 7Lec 7
Lec 7
 
MongoDB Europe 2016 - Graph Operations with MongoDB
MongoDB Europe 2016 - Graph Operations with MongoDBMongoDB Europe 2016 - Graph Operations with MongoDB
MongoDB Europe 2016 - Graph Operations with MongoDB
 
Analytics with MongoDB Aggregation Framework and Hadoop Connector
Analytics with MongoDB Aggregation Framework and Hadoop ConnectorAnalytics with MongoDB Aggregation Framework and Hadoop Connector
Analytics with MongoDB Aggregation Framework and Hadoop Connector
 
Data Processing and Aggregation with MongoDB
Data Processing and Aggregation with MongoDB Data Processing and Aggregation with MongoDB
Data Processing and Aggregation with MongoDB
 
4 sesame
4 sesame4 sesame
4 sesame
 

Ähnlich wie RESTful Web Applications with Google Go

Net/http and the http.handler interface
Net/http and the http.handler interfaceNet/http and the http.handler interface
Net/http and the http.handler interfaceJoakim Gustin
 
Net/http and the http.handler interface
Net/http and the http.handler interfaceNet/http and the http.handler interface
Net/http and the http.handler interfaceEvolve
 
Metadata Extraction and Content Transformation
Metadata Extraction and Content TransformationMetadata Extraction and Content Transformation
Metadata Extraction and Content TransformationAlfresco Software
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasyJBug Italy
 
外部環境への依存をテストする
外部環境への依存をテストする外部環境への依存をテストする
外部環境への依存をテストするShunsuke Maeda
 
神に近づくx/net/context (Finding God with x/net/context)
神に近づくx/net/context (Finding God with x/net/context)神に近づくx/net/context (Finding God with x/net/context)
神に近づくx/net/context (Finding God with x/net/context)guregu
 
Introduction to Ajax programming
Introduction to Ajax programmingIntroduction to Ajax programming
Introduction to Ajax programmingFulvio Corno
 
[Community Call] Ballerina Swan Lake HTTP Module Changes
[Community Call]  Ballerina Swan Lake HTTP Module Changes[Community Call]  Ballerina Swan Lake HTTP Module Changes
[Community Call] Ballerina Swan Lake HTTP Module ChangesBallerinalang
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The ApproachHaci Murat Yaman
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSCosmin Mereuta
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.pptWalaSidhom1
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web servicesnbuddharaju
 
jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - AjaxWebStackAcademy
 
Creating an Uber Clone - Part XII.pdf
Creating an Uber Clone - Part XII.pdfCreating an Uber Clone - Part XII.pdf
Creating an Uber Clone - Part XII.pdfShaiAlmog1
 

Ähnlich wie RESTful Web Applications with Google Go (20)

Net/http and the http.handler interface
Net/http and the http.handler interfaceNet/http and the http.handler interface
Net/http and the http.handler interface
 
Net/http and the http.handler interface
Net/http and the http.handler interfaceNet/http and the http.handler interface
Net/http and the http.handler interface
 
Ajax
AjaxAjax
Ajax
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
From Node to Go
From Node to GoFrom Node to Go
From Node to Go
 
Metadata Extraction and Content Transformation
Metadata Extraction and Content TransformationMetadata Extraction and Content Transformation
Metadata Extraction and Content Transformation
 
Power tools in Java
Power tools in JavaPower tools in Java
Power tools in Java
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
 
外部環境への依存をテストする
外部環境への依存をテストする外部環境への依存をテストする
外部環境への依存をテストする
 
神に近づくx/net/context (Finding God with x/net/context)
神に近づくx/net/context (Finding God with x/net/context)神に近づくx/net/context (Finding God with x/net/context)
神に近づくx/net/context (Finding God with x/net/context)
 
Introduction to Ajax programming
Introduction to Ajax programmingIntroduction to Ajax programming
Introduction to Ajax programming
 
[Community Call] Ballerina Swan Lake HTTP Module Changes
[Community Call]  Ballerina Swan Lake HTTP Module Changes[Community Call]  Ballerina Swan Lake HTTP Module Changes
[Community Call] Ballerina Swan Lake HTTP Module Changes
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The Approach
 
Server Side? Swift
Server Side? SwiftServer Side? Swift
Server Side? Swift
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JS
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web services
 
jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - Ajax
 
JavaScript Lessons 2023
JavaScript Lessons 2023JavaScript Lessons 2023
JavaScript Lessons 2023
 
Creating an Uber Clone - Part XII.pdf
Creating an Uber Clone - Part XII.pdfCreating an Uber Clone - Part XII.pdf
Creating an Uber Clone - Part XII.pdf
 

Mehr von Frank Müller

JAX 2023 - Cloud Provider APIs
JAX 2023 - Cloud Provider APIsJAX 2023 - Cloud Provider APIs
JAX 2023 - Cloud Provider APIsFrank Müller
 
JAX 2023 - Generics in Go
JAX 2023 - Generics in GoJAX 2023 - Generics in Go
JAX 2023 - Generics in GoFrank Müller
 
Let The Computer Do It
Let The Computer Do ItLet The Computer Do It
Let The Computer Do ItFrank Müller
 
2021 OOP - Kubernetes Operatoren
2021   OOP - Kubernetes Operatoren2021   OOP - Kubernetes Operatoren
2021 OOP - Kubernetes OperatorenFrank Müller
 
DevOpsCon - Verteilte Entwicklung in Go
DevOpsCon - Verteilte Entwicklung in GoDevOpsCon - Verteilte Entwicklung in Go
DevOpsCon - Verteilte Entwicklung in GoFrank Müller
 
Devs@Home - Einführung in Go
Devs@Home - Einführung in GoDevs@Home - Einführung in Go
Devs@Home - Einführung in GoFrank Müller
 
Blockchains - Mehr als nur digitale Währungen
Blockchains - Mehr als nur digitale WährungenBlockchains - Mehr als nur digitale Währungen
Blockchains - Mehr als nur digitale WährungenFrank Müller
 
Spaß an der Nebenläufigkeit
Spaß an der NebenläufigkeitSpaß an der Nebenläufigkeit
Spaß an der NebenläufigkeitFrank Müller
 
Go - Googles Sprache für skalierbare Systeme
Go - Googles Sprache für skalierbare SystemeGo - Googles Sprache für skalierbare Systeme
Go - Googles Sprache für skalierbare SystemeFrank Müller
 
Cloud Provisioning mit Juju
Cloud Provisioning mit JujuCloud Provisioning mit Juju
Cloud Provisioning mit JujuFrank Müller
 
Juju - Scalable Software with Google Go
Juju - Scalable Software with Google GoJuju - Scalable Software with Google Go
Juju - Scalable Software with Google GoFrank Müller
 
Clouds, leicht beherrschbar
Clouds, leicht beherrschbarClouds, leicht beherrschbar
Clouds, leicht beherrschbarFrank Müller
 
Skalierbare Anwendungen mit Google Go
Skalierbare Anwendungen mit Google GoSkalierbare Anwendungen mit Google Go
Skalierbare Anwendungen mit Google GoFrank Müller
 
WTC 2013 - Juju - Mit etwas Magie zur perfekten Cloud
WTC 2013 - Juju - Mit etwas Magie zur perfekten CloudWTC 2013 - Juju - Mit etwas Magie zur perfekten Cloud
WTC 2013 - Juju - Mit etwas Magie zur perfekten CloudFrank Müller
 
Juju - Google Go in a scalable Environment
Juju - Google Go in a scalable EnvironmentJuju - Google Go in a scalable Environment
Juju - Google Go in a scalable EnvironmentFrank Müller
 
OOP 2013 - Weltweite Entwicklung von Open Source Software
OOP 2013 - Weltweite Entwicklung von Open Source SoftwareOOP 2013 - Weltweite Entwicklung von Open Source Software
OOP 2013 - Weltweite Entwicklung von Open Source SoftwareFrank Müller
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of GoFrank Müller
 

Mehr von Frank Müller (20)

JAX 2023 - Cloud Provider APIs
JAX 2023 - Cloud Provider APIsJAX 2023 - Cloud Provider APIs
JAX 2023 - Cloud Provider APIs
 
JAX 2023 - Generics in Go
JAX 2023 - Generics in GoJAX 2023 - Generics in Go
JAX 2023 - Generics in Go
 
Let The Computer Do It
Let The Computer Do ItLet The Computer Do It
Let The Computer Do It
 
Concurrency with Go
Concurrency with GoConcurrency with Go
Concurrency with Go
 
2021 OOP - Kubernetes Operatoren
2021   OOP - Kubernetes Operatoren2021   OOP - Kubernetes Operatoren
2021 OOP - Kubernetes Operatoren
 
DevOpsCon - Verteilte Entwicklung in Go
DevOpsCon - Verteilte Entwicklung in GoDevOpsCon - Verteilte Entwicklung in Go
DevOpsCon - Verteilte Entwicklung in Go
 
Devs@Home - Einführung in Go
Devs@Home - Einführung in GoDevs@Home - Einführung in Go
Devs@Home - Einführung in Go
 
Fun with functions
Fun with functionsFun with functions
Fun with functions
 
Ein Gopher im Netz
Ein Gopher im NetzEin Gopher im Netz
Ein Gopher im Netz
 
Blockchains - Mehr als nur digitale Währungen
Blockchains - Mehr als nur digitale WährungenBlockchains - Mehr als nur digitale Währungen
Blockchains - Mehr als nur digitale Währungen
 
Spaß an der Nebenläufigkeit
Spaß an der NebenläufigkeitSpaß an der Nebenläufigkeit
Spaß an der Nebenläufigkeit
 
Go - Googles Sprache für skalierbare Systeme
Go - Googles Sprache für skalierbare SystemeGo - Googles Sprache für skalierbare Systeme
Go - Googles Sprache für skalierbare Systeme
 
Cloud Provisioning mit Juju
Cloud Provisioning mit JujuCloud Provisioning mit Juju
Cloud Provisioning mit Juju
 
Juju - Scalable Software with Google Go
Juju - Scalable Software with Google GoJuju - Scalable Software with Google Go
Juju - Scalable Software with Google Go
 
Clouds, leicht beherrschbar
Clouds, leicht beherrschbarClouds, leicht beherrschbar
Clouds, leicht beherrschbar
 
Skalierbare Anwendungen mit Google Go
Skalierbare Anwendungen mit Google GoSkalierbare Anwendungen mit Google Go
Skalierbare Anwendungen mit Google Go
 
WTC 2013 - Juju - Mit etwas Magie zur perfekten Cloud
WTC 2013 - Juju - Mit etwas Magie zur perfekten CloudWTC 2013 - Juju - Mit etwas Magie zur perfekten Cloud
WTC 2013 - Juju - Mit etwas Magie zur perfekten Cloud
 
Juju - Google Go in a scalable Environment
Juju - Google Go in a scalable EnvironmentJuju - Google Go in a scalable Environment
Juju - Google Go in a scalable Environment
 
OOP 2013 - Weltweite Entwicklung von Open Source Software
OOP 2013 - Weltweite Entwicklung von Open Source SoftwareOOP 2013 - Weltweite Entwicklung von Open Source Software
OOP 2013 - Weltweite Entwicklung von Open Source Software
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of Go
 

Kürzlich hochgeladen

SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 

Kürzlich hochgeladen (20)

SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 

RESTful Web Applications with Google Go

  • 2. Frank Müller Oldenburg / Germany Released Summer 1965 Software Engineer Author ! mue@tideland.biz blog.tideland.biz @themue github.com/tideland
  • 3. Goals • Usage of HTTP / HTTPS • Multiplexing based on path containing functional domain, resource, and possible resource id • List of multiple handles to support generic tasks like authentication and authorization • Mapping of HTTP methods to CRUD operations • Major data is JSON, but also XML and templates
  • 5. Go HTTP Package • Simple • Types implementing http.Handler interface or functions with a defined signature for handling • Integrated server able to handle HTTP and HTTPS • Not very convenient
  • 6. Go HTTP Package - Handler type MyHandler struct{} ! // Implementing http.Handler interface. func (mh *MyHandler) ServeHTTP( w http.ResponseWriter, r *http.Request) { w.Header().Set(”Content-Type”, ”text/plain”) w.WriteHeader(http.StatusOK) fmt.Fprintln(w, ”Hello, Go User Group!”) }
  • 7. Go HTTP Package - Main ! func main() { // Register handler for path. http.Handle(”/myHandler”, &MyHandler{}) ! // Start server on port 8080. log.Fatal(http.ListenAndServe(”:8080”, nil)) }
  • 8. ❝Simple tasks can be done using the standard library, but own powerful packages are easy to create. –Gopher
  • 10. Multiplexer • Go default uses a prefix based pattern • Our RWM maps based on domain and resource • Request and response wrapped into convenient context • Fallback to a default handler
  • 11. Multiplexer - Type // RESTfulWebMultiplexer is our own multiplexer. type RESTfulWebMultiplexer struct { mapping domains … } ! // AddHandler adds a handler based on domain and resource. func (mux * RESTfulWebMultiplexer) AddHandler( domain, resource string, h ResourceHandler) error { … }
  • 12. Multiplexer - Interface Method // ServeHTTP implements the handler interface. func (mux * RESTfulWebMultiplexer) ServeHTTP( w http.ResponseWriter, r *http.Request) { ctx := newContext(mux, w, r) if err := mux.mapping.handle(ctx); err != nil { … } }
  • 13. Multiplexer - Main ! func main() { // Create multiplexer and add handlers. mux := NewRESTfulWebMultiplexer() ! mux.AddHandler(”content”, ”blog”, NewBlogHandler()) … ! // Start server with our multiplexer on port 8080. log.Fatal(http.ListenAndServe(”:8080”, mux)) }
  • 14. ❝Own multiplexers make HTTP server more flexible. –Gopher
  • 15. Multiplexer - Domains // domains maps domains to their resources. type domains map[string]resources ! // handle retrieves the resources for the context domain and // lets them handle the context. func (d domains) handle( ctx *RequestContext) error { resources, ok := d[ctx.Domain] if !ok { resources = d[ctx.Mux.DefaultDomain()] } // Continue handling. return resources.handle(ctx) }
  • 16. Multiplexer - Resources // resources maps resources to their handler lists. type resources map[string]handlers ! // handle retrieves the handlers for the context resource and lets // them handle the context. func (r resources) handle( ctx *RequestContext) error { handlers, ok := r[ctx.Resource] if !ok { handlers = r[ctx.Mux.DefaultResource(ctx.Domain)] } // Continue handling. return handlers.handle(ctx) }
  • 17. Multiplexer - Handlers // handlers chains all handlers for one resource. type handlers []ResourceHandler ! // handle lets all handlers handle the context. func (h handlers) handle( ctx *RequestContext) error { for _, handler := range h { ok, err := ctx.Mux.dispatch(ctx, handler) if err != nil { return err } // Handler tells to stop, but w/o error. if !ok { return nil } } return nil }
  • 18. ❝Use my simple type system for small types with useful methods. –Gopher
  • 20. Resource Handler • Basic interface for initialization and read operation • Additional interfaces for create, update, and delete operations • Dispatcher to map HTTP methods
  • 21. Resource Handler - Base Interface // ResourceHandler defines the base interface. It handles the // HTTP GET method with Read(). type ResourceHandler interface { // Init is called after registration of the handler. Init(domain, resource string) error ! // Read is called if the HTTP method is GET. Read(ctx *Context) (bool, error) }
  • 22. Resource Handler - Create Interface // CreateResourceHandler defines the interface to additionally // handle the HTTP POST with Create(). type CreateResourceHandler interface { // Create is called if the HTTP method is POST. Create(ctx *Context) (bool, error) }
  • 23. Resource Handler - Dispatch // dispatch maps HTTP methods to handler function calls. func (mux *RESTfulWebMultiplexer) dispatch( ctx *Context, h ResourceHandler) (bool, error) { switch ctx.Request.Method { case ”GET”: return h.Read(ctx) case ”POST”: if ch, ok := h.(CreateResourceHandler); ok { return ch.Create(ctx) } return false, errors.New(”handler cannot process POST”) case … } return false, errors.New(”invalid HTTP method”) }
  • 24. ❝Small interfaces and type assertions are a powerful combination. –Gopher
  • 26. Context • Simple wrapper for request and response • Provides information about domain, resource and id • Also provides information about stuff like accepted content types and languages • Allows simpler reading and writing of JSON etc.
  • 27. Context - Type // Context encapsulates all needed data for handling a request. type Context struct { Mux *RESTfulWebMultiplexer Writer http.ResponseWriter Request *http.Request Domain, Resource, ResourceId string } ! // newContext creates a new context and parses the URL path. func newContext( mux *RESTfulWebMultiplexer, w http.ResponseWriter, r *http.Request) *Context { … }
  • 28. Context - Simple Request Analysis // accepts checks if the requestor accepts a content type. func (ctx *Context) accepts(ct string) bool { accept := ctx.Request.Header.Get(”Accept”) return strings.Contains(accept, ct) } ! // AcceptsJSON checks if the requestor accepts JSON as // a content type. func (ctx *Context) AcceptsJSON() bool { return ctx.accepts(”application/json”) }
  • 29. Context - Typical Operations // Redirect to a domain, resource and resource id (optional). func (ctx *Context) Redirect( domain, resource, resourceId string) { url := ctx.Mux.BasePath() + domain + ”/” + resource if resourceId != ”” { url += ”/” + resourceId } ctx.Writer.Header().Set(”Location”, url) ctx.Writer.WriteHeader(http.StatusMovedPermanently) }
  • 30. ❝Public fields are not evil as long as the data is not shared. –Gopher
  • 31. JSON Marshaling • Go likes JSON • Really! (scnr) • Automatically, controlled, and manually
  • 32. JSON - Standard // Public fields will be marshaled. type Demo struct { FieldA string FieldB int FieldC *OtherStruct fieldX bool // No, you won’t see me. } ! demo := &demo{ … } ! // b contains the marshaled demo struct as []byte. b, err := json.Marshal(demo)
  • 33. JSON - Controlled // Control with field tags. type AnotherDemo struct { FieldA string `json:”-”` // Ignore. FieldB int `json:”OtherName”` // Change name. FieldC float64 `json:”,string”` // As string. FieldD bool `json:”,omitempty”` // Ignore if empty. FieldE string // As usual. fieldX int // Still ignored. }
  • 34. JSON - Manually // User has to care for it. type StillADemo struct { fieldA string fieldB int } ! // MarshalJSON implements the Marshaler interface. func (d *StillADemo) MarshalJSON() ([]byte, error) { format := `{”First”: %q, ”Second”: %d}` json := fmt.Sprintf(format, d.fieldA, d.fieldB) return []byte(json), nil }
  • 35. JSON - Integrate in Context func (ctx *Context) RespondJSON( data interface{}, html bool) error { b, err := json.Marshal(data) if err != nil { return fmt.Errorf(”cannot respond JSON: %v”, err) } if html { var buf bytes.Buffer json.HTMLEscape(&buf, b) b = buf.Bytes() } ctx.Writer.Header().Set(”Content-Type”, ”application/json”) _, err = ctx.Writer.Write(b) return err }
  • 36. ❝My standard library provides powerful encoding packages, also for XML, CSV, ASN.1, etc. –Gopher
  • 38. Tags by Interest Browser Stat Handler Content Handler Tag Handler Content Backend Stat Backend DB GET /content/page/4711 GET /content/tags/interest Goroutines Async Update Page Request gets HTML JS Request gets JSON
  • 39. Stat Handler func (h *StatHandler) Read(ctx *rwm.Context) (bool, error) { if ctx.ResourceId != ”” { // Backend handles update in background. statBackend.UpdatePage(ctx.ResourceId) } return true, nil }
  • 40. Content Handler func (h *ContentHandler) Read( ctx *rwm.Context) (bool, error) { var page *Page if ctx.ResourceId != ”” { page = contentBackend.Page(ctx.ResourceId) } else { page = contentBackend.Index() } if err := ctx.RespondTemplate(h.template, page); err != nil { return false, err } return true, nil }
  • 41. Tag Handler func (h *StatHandler) Read(ctx *rwm.Context) (bool, error) { var err error switch ctx.ResourceId { case ”interest”: tags := statBackend.TagsByInterest() if ctx.AcceptsJSON() { err = ctx.RespondJSON(tags, true) } else if ctx.AcceptsXML() { err = ctx.RespondXML(tags) } case … } … }
  • 42. ❝Enjoy Go, it’s lightweight, simple and very productive. –Gopher
  • 43.
  • 44. ❝ Zitat hier eingeben. –Christian BauerImages 123RF iStockphoto Own Sources