SlideShare ist ein Scribd-Unternehmen logo
1 von 19
Downloaden Sie, um offline zu lesen
Building RESTful
Services with Go and
MongoDB
Shiju Varghese
GopherCon India 2015
20 February, 2015
● Cloud Solutions Architect
● Gopher
@shijucv
https://github.com/shijuvar
About Me
Outline
● Building HTTP Servers in Go.
● Working with MongoDB using mgo.
● REST API Demo with Go and MongoDB.
Building HTTP Servers
net/http Package
● Provides HTTP client and server
implementations.
● Allows you to build HTTP servers in Go.
● Provides composability and extensibility.
Processing HTTP Requests
● ServeMux - HTTP Request multiplexer
(router).
● Handler - Serve HTTP Requests.
http.Handler Interface
● Serve HTTP Requests.
● Handlers are responsible for writing
response headers and bodies.
type Handler interface {
ServeHTTP(ResponseWriter , *Request)
}
HandlerFunc
An adapter to allow the use of ordinary
functions as HTTP handlers.
type HandlerFunc func(ResponseWriter, *Request)
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
f(w, r)
}
A Simple HTTP Server
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello, world!")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe (":8080", nil)
}
Persistence with MongoDB
mgo (mango)
● MongoDB driver for the Go.
● Written in Go.
● Created in 2010.
● Sponsored by MongoDB from 2011.
Connecting to MongoDB
Dial establishes a new session to the cluster of
servers defined by the url parameter.
session, err := mgo.Dial( "localhost")
if err != nil {
return err
}
Working with Collections
collection := session.DB( "notesdb").C("notes")
var notes []Note
iter := collection.Find(nil).Iter()
result := Note{}
for iter.Next(&result) {
notes = append(notes, result)
}
c := session.DB(database).C(collection)
Querying against collections
Accessing collections
Demo - REST API with Go and
MongoDB
Model
type Note struct {
Id bson.ObjectId `bson:"_id" json:"id"`
Title string `json:"title"`
Description string `json:"description"`
CreatedOn time.Time `json:"createdon"`
}
Routing with gorilla/mux Package
r := mux.NewRouter()
r.HandleFunc("/api/notes", NotesHandler).Methods( "GET")
r.HandleFunc("/api/notes", CreateNoteHandler).Methods( "POST")
r.HandleFunc("/api/notes/{id}" , UpdateNoteHandler).Methods( "PUT")
r.HandleFunc("/api/notes/{id}" , DeleteNoteHandler).Methods( "DELETE")
Handler Functions
func CreateNoteHandler (w http.ResponseWriter, r *http.Request) {
}
func NotesHandler(w http.ResponseWriter, r *http.Request) {
}
func UpdateNoteHandler (w http.ResponseWriter, r *http.Request) {
}
func DeleteNoteHandler (w http.ResponseWriter, r *http.Request) {
}
Source Code
https://github.com/shijuvar/gophercon-rest-demo
Thank You
Github - https://github.com/shijuvar
Twitter - https://twitter.com/shijucv
Shiju Varghese

Weitere ähnliche Inhalte

Was ist angesagt?

Apache2 BootCamp : Serving Dynamic Content with CGI
Apache2 BootCamp : Serving Dynamic Content with CGIApache2 BootCamp : Serving Dynamic Content with CGI
Apache2 BootCamp : Serving Dynamic Content with CGI
Wildan Maulana
 
NATS in action - A Real time Microservices Architecture handled by NATS
NATS in action - A Real time Microservices Architecture handled by NATSNATS in action - A Real time Microservices Architecture handled by NATS
NATS in action - A Real time Microservices Architecture handled by NATS
Raül Pérez
 
Nginx - Tips and Tricks.
Nginx - Tips and Tricks.Nginx - Tips and Tricks.
Nginx - Tips and Tricks.
Harish S
 

Was ist angesagt? (20)

Apache2 BootCamp : Serving Dynamic Content with CGI
Apache2 BootCamp : Serving Dynamic Content with CGIApache2 BootCamp : Serving Dynamic Content with CGI
Apache2 BootCamp : Serving Dynamic Content with CGI
 
Developing a user-friendly OpenResty application
Developing a user-friendly OpenResty applicationDeveloping a user-friendly OpenResty application
Developing a user-friendly OpenResty application
 
Composer
ComposerComposer
Composer
 
gRPC & Kubernetes
gRPC & KubernetesgRPC & Kubernetes
gRPC & Kubernetes
 
NATS in action - A Real time Microservices Architecture handled by NATS
NATS in action - A Real time Microservices Architecture handled by NATSNATS in action - A Real time Microservices Architecture handled by NATS
NATS in action - A Real time Microservices Architecture handled by NATS
 
Introduction to Nginx
Introduction to NginxIntroduction to Nginx
Introduction to Nginx
 
Configuration Management - Finding the tool to fit your needs
Configuration Management - Finding the tool to fit your needsConfiguration Management - Finding the tool to fit your needs
Configuration Management - Finding the tool to fit your needs
 
OpenCms Days 2016: OpenCms at the swiss seismological service
OpenCms Days 2016: OpenCms at the swiss seismological serviceOpenCms Days 2016: OpenCms at the swiss seismological service
OpenCms Days 2016: OpenCms at the swiss seismological service
 
Fluentd v1.0 in a nutshell
Fluentd v1.0 in a nutshellFluentd v1.0 in a nutshell
Fluentd v1.0 in a nutshell
 
OpenCms Days 2015 Next generation repository
OpenCms Days 2015  Next generation repositoryOpenCms Days 2015  Next generation repository
OpenCms Days 2015 Next generation repository
 
OpenCms Days 2016: Next generation content repository
OpenCms Days 2016: Next generation content repository OpenCms Days 2016: Next generation content repository
OpenCms Days 2016: Next generation content repository
 
Nginx
NginxNginx
Nginx
 
NGINX 101 - now with more Docker
NGINX 101 - now with more DockerNGINX 101 - now with more Docker
NGINX 101 - now with more Docker
 
OpenCmsDays 2013 - Using OpenCms 9 folders as a network drive
OpenCmsDays 2013 - Using OpenCms 9 folders as a network driveOpenCmsDays 2013 - Using OpenCms 9 folders as a network drive
OpenCmsDays 2013 - Using OpenCms 9 folders as a network drive
 
Nginx Deep Dive Kubernetes Ingress
Nginx Deep Dive Kubernetes IngressNginx Deep Dive Kubernetes Ingress
Nginx Deep Dive Kubernetes Ingress
 
Nginx in production
Nginx in productionNginx in production
Nginx in production
 
Arkena from heroku_to_k8s
Arkena from heroku_to_k8sArkena from heroku_to_k8s
Arkena from heroku_to_k8s
 
Nginx - Tips and Tricks.
Nginx - Tips and Tricks.Nginx - Tips and Tricks.
Nginx - Tips and Tricks.
 
Melbourne User Group OAK and MongoDB
Melbourne User Group OAK and MongoDBMelbourne User Group OAK and MongoDB
Melbourne User Group OAK and MongoDB
 
Webserver
WebserverWebserver
Webserver
 

Ähnlich wie Building RESTful Services With Go and MongoDB

Java web programming
Java web programmingJava web programming
Java web programming
Ching Yi Chan
 
Mearn Stack Web Development(Http Presentation)
Mearn Stack Web Development(Http Presentation)Mearn Stack Web Development(Http Presentation)
Mearn Stack Web Development(Http Presentation)
VASUOFFICIAL
 

Ähnlich wie Building RESTful Services With Go and MongoDB (20)

202107 - Orion introduction - COSCUP
202107 - Orion introduction - COSCUP202107 - Orion introduction - COSCUP
202107 - Orion introduction - COSCUP
 
Java web programming
Java web programmingJava web programming
Java web programming
 
Declarative Clients in Spring
Declarative Clients in SpringDeclarative Clients in Spring
Declarative Clients in Spring
 
Driving containerd operations with gRPC
Driving containerd operations with gRPCDriving containerd operations with gRPC
Driving containerd operations with gRPC
 
Restlet Framework NG
Restlet Framework NGRestlet Framework NG
Restlet Framework NG
 
Restlet Framework NG
Restlet Framework NGRestlet Framework NG
Restlet Framework NG
 
Using Go to build a REST API: yes, it’s a good match! - Vincent BEHAR & Mina ...
Using Go to build a REST API: yes, it’s a good match! - Vincent BEHAR & Mina ...Using Go to build a REST API: yes, it’s a good match! - Vincent BEHAR & Mina ...
Using Go to build a REST API: yes, it’s a good match! - Vincent BEHAR & Mina ...
 
Extending Retrofit for fun and profit
Extending Retrofit for fun and profitExtending Retrofit for fun and profit
Extending Retrofit for fun and profit
 
Mearn Stack Web Development(Http Presentation)
Mearn Stack Web Development(Http Presentation)Mearn Stack Web Development(Http Presentation)
Mearn Stack Web Development(Http Presentation)
 
KrakenD API Gateway
KrakenD API GatewayKrakenD API Gateway
KrakenD API Gateway
 
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
 
Angular 4 The new Http Client Module
Angular 4 The new Http Client ModuleAngular 4 The new Http Client Module
Angular 4 The new Http Client Module
 
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
 
Rest service in mule
Rest service in mule Rest service in mule
Rest service in mule
 
Clojure and the Web
Clojure and the WebClojure and the Web
Clojure and the Web
 
Webinar: Draw a line between HTTP/2 client and HTTP Client
Webinar: Draw a line between HTTP/2 client and HTTP ClientWebinar: Draw a line between HTTP/2 client and HTTP Client
Webinar: Draw a line between HTTP/2 client and HTTP Client
 
Servlets
ServletsServlets
Servlets
 
Rest Service In Mule
Rest Service In Mule Rest Service In Mule
Rest Service In Mule
 
Spring 4 Web App
Spring 4 Web AppSpring 4 Web App
Spring 4 Web App
 
5-WebServers.ppt
5-WebServers.ppt5-WebServers.ppt
5-WebServers.ppt
 

Mehr von Shiju Varghese

Mehr von Shiju Varghese (20)

Building Modern Distributed Applications in Go with Service Weaver
Building Modern Distributed Applications in Go with Service WeaverBuilding Modern Distributed Applications in Go with Service Weaver
Building Modern Distributed Applications in Go with Service Weaver
 
Microservices in Go with Go kit
Microservices in Go with Go kitMicroservices in Go with Go kit
Microservices in Go with Go kit
 
NATS: A Cloud Native Messaging System
NATS: A Cloud Native Messaging SystemNATS: A Cloud Native Messaging System
NATS: A Cloud Native Messaging System
 
Event-Driven Microservices With NATS Streaming
Event-Driven Microservices With NATS StreamingEvent-Driven Microservices With NATS Streaming
Event-Driven Microservices With NATS Streaming
 
Inter-Process Communication in Microservices using gRPC
Inter-Process Communication in Microservices using gRPCInter-Process Communication in Microservices using gRPC
Inter-Process Communication in Microservices using gRPC
 
Building Microservices with gRPC and NATS
Building Microservices with gRPC and NATSBuilding Microservices with gRPC and NATS
Building Microservices with gRPC and NATS
 
Building High Performance APIs In Go Using gRPC And Protocol Buffers
Building High Performance APIs In Go Using gRPC And Protocol BuffersBuilding High Performance APIs In Go Using gRPC And Protocol Buffers
Building High Performance APIs In Go Using gRPC And Protocol Buffers
 
Building Scalable Backends with Go
Building Scalable Backends with GoBuilding Scalable Backends with Go
Building Scalable Backends with Go
 
A Primer to Containerization & Microservices
A Primer to Containerization & MicroservicesA Primer to Containerization & Microservices
A Primer to Containerization & Microservices
 
Docker and Kubernetes
Docker and KubernetesDocker and Kubernetes
Docker and Kubernetes
 
Practicing Mindfulness
Practicing MindfulnessPracticing Mindfulness
Practicing Mindfulness
 
Azure DocumentDB
Azure DocumentDBAzure DocumentDB
Azure DocumentDB
 
Azure Mobile Services .NET Backend
Azure Mobile Services .NET BackendAzure Mobile Services .NET Backend
Azure Mobile Services .NET Backend
 
Windows Azure Mobile Services
Windows Azure Mobile ServicesWindows Azure Mobile Services
Windows Azure Mobile Services
 
JavaScript, Meet Cloud : Node.js on Windows Azure
JavaScript, Meet Cloud : Node.js on Windows AzureJavaScript, Meet Cloud : Node.js on Windows Azure
JavaScript, Meet Cloud : Node.js on Windows Azure
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
Windows Azure Cloud Services
Windows Azure Cloud Services Windows Azure Cloud Services
Windows Azure Cloud Services
 
Windows Azure Webs Sites
Windows Azure Webs SitesWindows Azure Webs Sites
Windows Azure Webs Sites
 
Building Apps with Node.js
Building Apps with Node.jsBuilding Apps with Node.js
Building Apps with Node.js
 
Node on Windows Azure
Node on Windows AzureNode on Windows Azure
Node on Windows Azure
 

Kürzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

Building RESTful Services With Go and MongoDB

  • 1. Building RESTful Services with Go and MongoDB Shiju Varghese GopherCon India 2015 20 February, 2015
  • 2. ● Cloud Solutions Architect ● Gopher @shijucv https://github.com/shijuvar About Me
  • 3. Outline ● Building HTTP Servers in Go. ● Working with MongoDB using mgo. ● REST API Demo with Go and MongoDB.
  • 5. net/http Package ● Provides HTTP client and server implementations. ● Allows you to build HTTP servers in Go. ● Provides composability and extensibility.
  • 6. Processing HTTP Requests ● ServeMux - HTTP Request multiplexer (router). ● Handler - Serve HTTP Requests.
  • 7. http.Handler Interface ● Serve HTTP Requests. ● Handlers are responsible for writing response headers and bodies. type Handler interface { ServeHTTP(ResponseWriter , *Request) }
  • 8. HandlerFunc An adapter to allow the use of ordinary functions as HTTP handlers. type HandlerFunc func(ResponseWriter, *Request) func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) { f(w, r) }
  • 9. A Simple HTTP Server package main import ( "fmt" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello, world!") } func main() { http.HandleFunc("/", handler) http.ListenAndServe (":8080", nil) }
  • 11. mgo (mango) ● MongoDB driver for the Go. ● Written in Go. ● Created in 2010. ● Sponsored by MongoDB from 2011.
  • 12. Connecting to MongoDB Dial establishes a new session to the cluster of servers defined by the url parameter. session, err := mgo.Dial( "localhost") if err != nil { return err }
  • 13. Working with Collections collection := session.DB( "notesdb").C("notes") var notes []Note iter := collection.Find(nil).Iter() result := Note{} for iter.Next(&result) { notes = append(notes, result) } c := session.DB(database).C(collection) Querying against collections Accessing collections
  • 14. Demo - REST API with Go and MongoDB
  • 15. Model type Note struct { Id bson.ObjectId `bson:"_id" json:"id"` Title string `json:"title"` Description string `json:"description"` CreatedOn time.Time `json:"createdon"` }
  • 16. Routing with gorilla/mux Package r := mux.NewRouter() r.HandleFunc("/api/notes", NotesHandler).Methods( "GET") r.HandleFunc("/api/notes", CreateNoteHandler).Methods( "POST") r.HandleFunc("/api/notes/{id}" , UpdateNoteHandler).Methods( "PUT") r.HandleFunc("/api/notes/{id}" , DeleteNoteHandler).Methods( "DELETE")
  • 17. Handler Functions func CreateNoteHandler (w http.ResponseWriter, r *http.Request) { } func NotesHandler(w http.ResponseWriter, r *http.Request) { } func UpdateNoteHandler (w http.ResponseWriter, r *http.Request) { } func DeleteNoteHandler (w http.ResponseWriter, r *http.Request) { }
  • 19. Thank You Github - https://github.com/shijuvar Twitter - https://twitter.com/shijucv Shiju Varghese