This presentation covers how I wrote a little 39 line Node program and adapted it into an 88 line Go program. Serves as a "show me the code" example of getting started with Go.
Code is available at: https://github.com/agileleague/httpwebsockettest
The Node server in this project is hosted on Heroku at: http://httpwebsocketspeedtest.herokuapp.com/
This is my presentation from TechBeats #3 hosted by Applause about Server-Side Swift framework called Vapor.
Swift is a great language and possibility of using it also in backend is a huge benefit for any iOS developer out there. Using Vapor is a seamless experience. With this framework creating advance APIs by iOS developer is as easy as writing simple iOS app.
https://www.meetup.com/TechBeats-hosted-by-Applause/events/254910023/
Small Node.js proxy to turn a paginated JSON REST API into a CSV streaming download. Examples of code and patterns.
Presented at the London Node User Group meetup, April 2014
Roll Your Own API Management Platform with nginx and LuaJon Moore
We recently replaced a proprietary API management solution with an in-house implementation built with nginx and Lua that let us get to a continuous delivery practice in a handful of months. Learn about our development process and the overall architecture that allowed us to write minimal amounts of code, enjoying native code performance while permitting interactive codeing, and how we leveraged other open source tools like Vagrant, Ansible, and OpenStack to build an automation-rich delivery pipeline. We will also take an in-depth look at our capacity management approach that differs from the rate limiting concept prevalent in the API community.
This is my presentation from TechBeats #3 hosted by Applause about Server-Side Swift framework called Vapor.
Swift is a great language and possibility of using it also in backend is a huge benefit for any iOS developer out there. Using Vapor is a seamless experience. With this framework creating advance APIs by iOS developer is as easy as writing simple iOS app.
https://www.meetup.com/TechBeats-hosted-by-Applause/events/254910023/
Small Node.js proxy to turn a paginated JSON REST API into a CSV streaming download. Examples of code and patterns.
Presented at the London Node User Group meetup, April 2014
Roll Your Own API Management Platform with nginx and LuaJon Moore
We recently replaced a proprietary API management solution with an in-house implementation built with nginx and Lua that let us get to a continuous delivery practice in a handful of months. Learn about our development process and the overall architecture that allowed us to write minimal amounts of code, enjoying native code performance while permitting interactive codeing, and how we leveraged other open source tools like Vagrant, Ansible, and OpenStack to build an automation-rich delivery pipeline. We will also take an in-depth look at our capacity management approach that differs from the rate limiting concept prevalent in the API community.
Integrating icinga2 and the HashiCorp suiteBram Vogelaar
We all love infrastructure as code, we automate everything ™ but how many
of us can really say we could destroy and recreate our core infrastructure
without human intervention. Can you be sure there isnt a DNS problem or
that all the things ™ are done in the right order This talk walks the
audience through a green fields exercise that sets up service discovery
using Consul, infrastructure as code using terraform, using images build
with packer and configured using puppet.
A gentle introduction to Observability and how to setup a highly available monitoring platform accros multiple datacenters.
During this talk we will investigate how we can setup and monitor an monitoring setup accross 2 DCs using Prometheus, Loki, Tempo, Alertmanager and Grafana. monitoring some services with some lessons learned along the way.
We all love infrastructure as code, we automate everything ™ but how many
of us can really say we could destroy and recreate our core infrastructure
without human intervention. Can you be sure there isnt a DNS problem or
that all the things ™ are done in the right order This talk walks the
audience through a green fields exercise that sets up service discovery
using Consul, infrastructure as code using terraform, using images build
with packer and configured using puppet.
A gentle introduction to Observability and how to setup a highly available monitoring platform across multiple datacenters.
During this talk we will investigate how we can setup and monitor an monitoring setup across 2 DCs using Prometheus, Loki, Tempo, Alertmanager and Grafana. monitoring some services with some lessons learned along the way.
Server-Side Push: Comet, Web Sockets come of age (OSCON 2013)Brian Sam-Bodden
Server-side browser push technologies have been around for a while in one way or another, ranging from from crude browser polling to Flash enabled frameworks. In this session you’ll get a code-driven walk-through on the evolution and mechanics of server-push technologies, including:
Server streaming
Polling and long Polling
Comet
Web Sockets
Building Your First Data Science Applicatino in MongoDBMongoDB
Speaker: Robyn Allen, Software Engineer, Central Inventions
Level: 100 (Beginner)
Track: Tutorials
To provide a hands-on opportunity to work with real data, this session will center around a web-hosted quiz application which helps students practice math and memorize vocabulary. After experimenting with a small demonstration dataset (generated by each individual during the workshop), attendees will be guided through working with an anonymized dataset in MongoDB. No prior MongoDB experience is required but attendees are expected to download and install MongoDB Community Edition (available for free from mongodb.com) and have a working Python 3 environment of their choice (e.g., IDLE, free from python.org) installed on a laptop they bring to the workshop.
Prerequisites:
Attendees are expected to bring a laptop with the following software installed:
MongoDB 3.4.x Community Edition
The text editor or IDE of their choice
A working Python 3 environment of their choice
No prior MongoDB experience is required.
What You Will Learn:
- How to load a CSV file into MongoDB using mongoimport and then write queries (using the Mongo shell) to ensure the data appears as expected. Attendees will use a demo version of an online quiz app to generate a small data file of raw session data (which can be accessed via http://strawnoodle.com/api/testdata after logging in to the demo app and answering one or more quiz questions about MongoDB). After studying how the demo app stores session data, attendees will practice using mongoimport to import anonymized session data (provided during the workshop) into MongoDB.
- How to use the aggregation pipeline (in PyMongo) to implement more complicated queries and gain insights from data. Because the sample dataset contains data from a variety of users of different skill levels, queries can be designed which reveal summary statistics for the anonymous user cohort or specific performance of individual users. Participants will receive instruction in using MongoDB aggregation pipelines in order to write powerful, efficient queries with very few lines of code.
- How to write queries to analyze sample data from an online quiz app. Once the sample data has been loaded into MongoDB, participants will be guided in writing basic queries to examine the sample data. Participants will have an opportunity to write queries in the Mongo shell and in Python in order to familiarize themselves with syntax variations and key ideas. Participants will learn how to implement CRUD operations in PyMongo.
Scalable Architecture Design
DEVIEW 2013 에서 발표한 "오픈소스를 활용한 분산 아키텍처 구현기술" 장표입니다.
Scalable Architecture 디자인을 위해 필요한 다양한 구현 기술 중 몇가지를 소개해 드립니다.
관련된 내용으로 문의 있으시면 메일로 연락 주세요~
Integrating icinga2 and the HashiCorp suiteBram Vogelaar
We all love infrastructure as code, we automate everything ™ but how many
of us can really say we could destroy and recreate our core infrastructure
without human intervention. Can you be sure there isnt a DNS problem or
that all the things ™ are done in the right order This talk walks the
audience through a green fields exercise that sets up service discovery
using Consul, infrastructure as code using terraform, using images build
with packer and configured using puppet.
A gentle introduction to Observability and how to setup a highly available monitoring platform accros multiple datacenters.
During this talk we will investigate how we can setup and monitor an monitoring setup accross 2 DCs using Prometheus, Loki, Tempo, Alertmanager and Grafana. monitoring some services with some lessons learned along the way.
We all love infrastructure as code, we automate everything ™ but how many
of us can really say we could destroy and recreate our core infrastructure
without human intervention. Can you be sure there isnt a DNS problem or
that all the things ™ are done in the right order This talk walks the
audience through a green fields exercise that sets up service discovery
using Consul, infrastructure as code using terraform, using images build
with packer and configured using puppet.
A gentle introduction to Observability and how to setup a highly available monitoring platform across multiple datacenters.
During this talk we will investigate how we can setup and monitor an monitoring setup across 2 DCs using Prometheus, Loki, Tempo, Alertmanager and Grafana. monitoring some services with some lessons learned along the way.
Server-Side Push: Comet, Web Sockets come of age (OSCON 2013)Brian Sam-Bodden
Server-side browser push technologies have been around for a while in one way or another, ranging from from crude browser polling to Flash enabled frameworks. In this session you’ll get a code-driven walk-through on the evolution and mechanics of server-push technologies, including:
Server streaming
Polling and long Polling
Comet
Web Sockets
Building Your First Data Science Applicatino in MongoDBMongoDB
Speaker: Robyn Allen, Software Engineer, Central Inventions
Level: 100 (Beginner)
Track: Tutorials
To provide a hands-on opportunity to work with real data, this session will center around a web-hosted quiz application which helps students practice math and memorize vocabulary. After experimenting with a small demonstration dataset (generated by each individual during the workshop), attendees will be guided through working with an anonymized dataset in MongoDB. No prior MongoDB experience is required but attendees are expected to download and install MongoDB Community Edition (available for free from mongodb.com) and have a working Python 3 environment of their choice (e.g., IDLE, free from python.org) installed on a laptop they bring to the workshop.
Prerequisites:
Attendees are expected to bring a laptop with the following software installed:
MongoDB 3.4.x Community Edition
The text editor or IDE of their choice
A working Python 3 environment of their choice
No prior MongoDB experience is required.
What You Will Learn:
- How to load a CSV file into MongoDB using mongoimport and then write queries (using the Mongo shell) to ensure the data appears as expected. Attendees will use a demo version of an online quiz app to generate a small data file of raw session data (which can be accessed via http://strawnoodle.com/api/testdata after logging in to the demo app and answering one or more quiz questions about MongoDB). After studying how the demo app stores session data, attendees will practice using mongoimport to import anonymized session data (provided during the workshop) into MongoDB.
- How to use the aggregation pipeline (in PyMongo) to implement more complicated queries and gain insights from data. Because the sample dataset contains data from a variety of users of different skill levels, queries can be designed which reveal summary statistics for the anonymous user cohort or specific performance of individual users. Participants will receive instruction in using MongoDB aggregation pipelines in order to write powerful, efficient queries with very few lines of code.
- How to write queries to analyze sample data from an online quiz app. Once the sample data has been loaded into MongoDB, participants will be guided in writing basic queries to examine the sample data. Participants will have an opportunity to write queries in the Mongo shell and in Python in order to familiarize themselves with syntax variations and key ideas. Participants will learn how to implement CRUD operations in PyMongo.
Scalable Architecture Design
DEVIEW 2013 에서 발표한 "오픈소스를 활용한 분산 아키텍처 구현기술" 장표입니다.
Scalable Architecture 디자인을 위해 필요한 다양한 구현 기술 중 몇가지를 소개해 드립니다.
관련된 내용으로 문의 있으시면 메일로 연락 주세요~
Success is something that all people strive for daily! However, as a brand, company or service provider, there are things that you can do to maximize your potential for success!
There are many ways in which an individual can make his success wherein one has to realize about oneself, identifying their passions and interests which are required for setting up goals to give color to life. These goals can be a short term one or a long term one and to achieve them you need to pay attention to your actions and cherish your life by enjoying the most of it. Being educated lets you acquire knowledge, skills and lets you to harness the maximum out of you with apprenticeships and long term training to boost your confidence. No Matter how much you earn, managing your finance is indeed essential and need to keep a track on your expenses and plan accordingly.
Learning in a Multi-device World Infographic explores the Multidevice World and explains how you can get started with multi-device learning. Get a comprehensive insight into creating, testing and delivering learning across a plethora of devices.
These are slides from a lecture given at the UC Berkeley School of Information for the Analyzing Big Data with Twitter class. A video of the talk can be found at http://blogs.ischool.berkeley.edu/i290-abdt-s12/2012/08/31/video-lecture-posted-intro-to-hadoop/
17 Ways Successful People Approach LifeBrian Downard
Do you want to know what makes successful people they way they are? Want to know what their secret is?
While success means something different to everyone, there are a few common things you can learn from other successful people that apply to anything you want to do in life.
Best Marketing Advice - 100 Global Experts Share Their Career WisdomHeidi Cohen
Looking to break into Marketing, PR or Social Media? Then read the best marketing career advice for recent graduates from 100 global experts. Includes Twitter & reading list.
Async/await is a new language feature that will ship with Swift 5.5 this year. There’s no doubt it will have a significant impact on how we write asynchronous code.
In this talk, we’re going to look at some use cases for async/await, how we can call existing Swift APIs using this new feature, and why your decision to write your SDK in Objective-C might turn out to have been a very clever move.
We’ll also have a look at the refactoring support Apple is adding to Xcode and how it will help you migrate your existing code base.
Node has captured the attention of early adopters by clearly differentiating itself as being asynchronous from the ground up while remaining accessible. Now that server side JavaScript is at the cutting edge of the asynchronous, real time web, it is in a much better position to establish itself as the go to language for also making synchronous, CRUD webapps and gain a stronger foothold on the server.
This talk covers the current state of server side JavaScript beyond Node. It introduces Common Node, a synchronous CommonJS compatibility layer using node-fibers which bridges the gap between the different platforms. We look into Common Node's internals, compare its performance to that of other implementations such as RingoJS and go through some ideal use cases.
Node.JS is a popular server-side JavaScript framework for handling real-time and distributed data processing. In this session you'll learn what Node.JS is, how it works under the hood, and what scenarios it's useful for. You'll also learn how to deploy it to Windows Azure and manage it inside of IIS 7.
Sharding and Load Balancing in Scala - Twitter's FinagleGeoff Ballinger
My presentation at Mostly Functional (http://mostlyfunctional.com), part of this year's Turing Festival Fringe (http://turingfestival.com) in Edinburgh. The example source code is up on Github at https://github.com/geoffballinger/simple-sharder
A language for the Internet: Why JavaScript and Node.js is right for Internet...Tom Croucher
Increasingly we want to do more with the web and Internet applications we build. We have more features, more data, more users, more devices and all of it needs to be in real-time. With all of these demands how can we keep up? The answer is choosing a language and a platform that are optimized for the kind of architecture Internet and web applications really have. The traditional approach prioritises computation, assigning server resources before they are actually needed. JavaScript and Node.js both take an event driven approach only assigning resources to events as they happen. This allows us to make dramatic gains in performance and resource utilization while still having an environment which is fun and easy to program.
SOAP Web Services have a well established role in the enterprise, but aside from the many benefits of the WS-* standards, SOAP and XML also carry additional baggage for developers. Consequently, REST Web Services are gaining tremendous popularity within the developer community. This session will begin by comparing and contrasting the basic concepts of both SOAP and REST Web Services. Building on that foundation, Sam Brannen will show attendees how to implement SOAP-based applications using Spring-WS 2.0. He will then demonstrate how to build a similar REST-ful application using Spring MVC 3.0. The session will conclude with an in-depth look at both server-side and client-side development as well as efficient integration testing of Web Services using the Spring Framework.
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
20. Capitalization is important
• Identifiers (functions, methods, and types) are
only exported if they are capitalized
• No public/private keywords
21. Static Typing
• Type of every identifier is set and cannot be altered!
• Variables (function parameters and locals)!
• Return values!
• Elements of Structs, Maps, and Slices!
• Channels!
• Compile time enforcement!
• Function arguments are passed by value
22. Concurrency Support
• Goroutines!
• Any function can be called under its own
Goroutine!
• Go organizes threads/processes internally!
• Channels!
• How Goroutines communicate
23. package main
import (
"net/http"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"time"
"encoding/json"
"fmt"
"os"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/xhr", handleXHR)
r.HandleFunc("/ws", handleWS)
r.PathPrefix("/").Handler(
Web Server
http.FileServer(http.Dir("./public/")),
)
24. "os"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/xhr", handleXHR)
r.HandleFunc("/ws", handleWS)
r.PathPrefix("/").Handler(
Web Server
http.FileServer(http.Dir("./public/")),
)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
fmt.Printf("listening on %sn", port)
http.ListenAndServe(":" + port, r)
}
func handleXHR(w http.ResponseWriter, r *http.Request) {
if r.FormValue("delay") == "1" {
time.Sleep(100 * time.Millisecond)
}
response, _ := json.Marshal(WebResponse{time.Now()})
w.Write(response)
25. "os"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/xhr", handleXHR)
r.HandleFunc("/ws", handleWS)
r.PathPrefix("/").Handler(
main()
http.FileServer(http.Dir("./public/")),
)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
fmt.Printf("listening on %sn", port)
http.ListenAndServe(":" + port, r)
}
func handleXHR(w http.ResponseWriter, r
*http.Request) {
26. if port == "" {
port = "8080"
}
HTTP request handler
fmt.Printf("listening on %sn", port)
http.ListenAndServe(":" + port, r)
}
func handleXHR(w http.ResponseWriter, r *http.Request) {
if r.FormValue("delay") == "1" {
time.Sleep(100 * time.Millisecond)
}
response, _ := json.Marshal(WebResponse{time.Now()})
w.Write(response)
}
type WebResponse struct {
Now time.Time `json:"now"`
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
27. if port == "" {
port = "8080"
}
JSON serialization
fmt.Printf("listening on %sn", port)
http.ListenAndServe(":" + port, r)
}
func handleXHR(w http.ResponseWriter, r *http.Request) {
if r.FormValue("delay") == "1" {
time.Sleep(100 * time.Millisecond)
}
response, _ := json.Marshal(WebResponse{time.Now()})
w.Write(response)
}
type WebResponse struct {
Now time.Time `json:"now"`
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
28. if port == "" {
port = "8080"
}
JSON serialization
fmt.Printf("listening on %sn", port)
http.ListenAndServe(":" + port, r)
}
func handleXHR(w http.ResponseWriter, r *http.Request) {
if r.FormValue("delay") == "1" {
time.Sleep(100 * time.Millisecond)
}
response, _ := json.Marshal(WebResponse{time.Now()})
w.Write(response)
}
type WebResponse struct {
Now time.Time `json:"now"`
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
29. "fmt"
"os"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/xhr", handleXHR)
r.HandleFunc("/ws", handleWS)
r.PathPrefix("/").Handler(
http.FileServer(http.Dir("./public/")),
)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
fmt.Printf("listening on %sn", port)
http.ListenAndServe(":" + port, r)
}
func handleXHR(w http.ResponseWriter, r *http.Request) {
if r.FormValue("delay") == "1" {
time.Sleep(100 * time.Millisecond)
}
response, _ := json.Marshal(WebResponse{time.Now()})
w.Write(response)
}
type WebResponse struct {
Now time.Time `json:"now"`
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
Web Server
30. w.Write(response)
}
type WebResponse struct {
Now time.Time `json:"now"`
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func handleWS(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
writes := make(chan WSResponse)
go respondWS(conn, writes)
for {
message := WSRequest{}
err := conn.ReadJSON(&message)
if err != nil {
close(writes)
return
}
go message.respond(writes)
}
}
func respondWS(conn *websocket.Conn,
writes chan WSResponse) {
for {
content, more := <-writes
conn.WriteJSON(content)
if !more {
return
}
}
}
type WSRequest struct {
Id int `json:id`
Delay bool `json:delay`
}
func (request *WSRequest) respond(
writes chan WSResponse) {
if request.Delay {
time.Sleep(100 * time.Millisecond)
}
response := WSResponse{time.Now(), request.Id}
writes <- response
}
type WSResponse struct {
Now time.Time `json:"now"`
Id int `json:"id"`
}
WebSocket Server
31. "os"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/xhr", handleXHR)
r.HandleFunc("/ws", handleWS)
r.PathPrefix("/").Handler(
Integration with Web Server
http.FileServer(http.Dir("./public/")),
)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
fmt.Printf("listening on %sn", port)
http.ListenAndServe(":" + port, r)
}
func handleXHR(w http.ResponseWriter, r
*http.Request) {
if r.FormValue("delay") == "1" {
32. ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func handleWS(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
writes := make(chan WSResponse)
go respondWS(conn, writes)
for {
message := WSRequest{}
err := conn.ReadJSON(&message)
if err != nil {
WebSocket Server
close(writes)
return
}
go message.respond(writes)
}
}
func respondWS(conn *websocket.Conn,
writes chan WSResponse) {
33. Now time.Time `json:"now"`
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func handleWS(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
writes := make(chan WSResponse)
go respondWS(conn, writes)
for {
message := WSRequest{}
err := conn.ReadJSON(&message)
if err != nil {
close(writes)
return
}
go message.respond(writes)
}
Open Connection
34. ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func handleWS(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
writes := make(chan WSResponse)
go respondWS(conn, writes)
for {
message := WSRequest{}
err := conn.ReadJSON(&message)
if err != nil {
WebSocket Server
close(writes)
return
}
go message.respond(writes)
}
}
func respondWS(conn *websocket.Conn,
writes chan WSResponse) {
35. Order of operations
1. Listen for new messages
2. Send the responses
3. Then close the connection
36. Order of implementation
1. Send the responses
2. Listen for new messages
3. Then close the connection
37. ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func handleWS(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
writes := make(chan WSResponse)
go respondWS(conn, writes)
for {
message := WSRequest{}
err := conn.ReadJSON(&message)
if err != nil {
WebSocket Server
close(writes)
return
}
go message.respond(writes)
}
}
func respondWS(conn *websocket.Conn,
writes chan WSResponse) {
41. ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
Listen on Connection
func handleWS(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
writes := make(chan WSResponse)
go respondWS(conn, writes)
for {
message := WSRequest{}
err := conn.ReadJSON(&message)
if err != nil {
close(writes)
return
}
go message.respond(writes)
}
}
func respondWS(conn *websocket.Conn,
writes chan WSResponse) {
42. }
}
type WSRequest struct {
Id int `json:id`
Delay bool `json:delay`
}
func (request *WSRequest) respond(
writes chan WSResponse) {
if request.Delay {
time.Sleep(100 * time.Millisecond)
}
response := WSResponse{time.Now(), request.Id}
writes <- response
}
type WSResponse struct {
Now time.Time `json:"now"`
Id int `json:"id"`
}
Build Response
43. package main
import (
"net/http"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"time"
"encoding/json"
"fmt"
"os"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/xhr", handleXHR)
r.HandleFunc("/ws", handleWS)
r.PathPrefix("/").Handler(
http.FileServer(http.Dir("./public/")),
)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
fmt.Printf("listening on %sn", port)
http.ListenAndServe(":" + port, r)
}
func handleXHR(w http.ResponseWriter, r *http.Request) {
if r.FormValue("delay") == "1" {
time.Sleep(100 * time.Millisecond)
}
response, _ := json.Marshal(WebResponse{time.Now()})
w.Write(response)
}
type WebResponse struct {
Now time.Time `json:"now"`
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func handleWS(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
writes := make(chan WSResponse)
go respondWS(conn, writes)
for {
message := WSRequest{}
err := conn.ReadJSON(&message)
if err != nil {
close(writes)
return
}
go message.respond(writes)
}
}
func respondWS(conn *websocket.Conn,
writes chan WSResponse) {
for {
content, more := <-writes
conn.WriteJSON(content)
if !more {
return
}
}
}
type WSRequest struct {
Id int `json:id`
Delay bool `json:delay`
}
func (request *WSRequest) respond(
writes chan WSResponse) {
if request.Delay {
time.Sleep(100 * time.Millisecond)
}
response := WSResponse{time.Now(), request.Id}
writes <- response
}
type WSResponse struct {
Now time.Time `json:"now"`
Id int `json:"id"`
}
Go Server
44. What’s the score?
• 88 lines of Go vs 39 lines of JavaScript!
• JSON interaction was kind of clunky!
• Haven’t figured out how to deploy to Heroku!
• Doing what the cool kids are doing
45. “ A straightforward translation of a C++
or Java program into Go is unlikely to
produce a satisfactory result—Java
programs are written in Java, not Go.”
–Effective Go
46. “ A straightforward translation of a C++
or Java JavaScript program into Go is
unlikely to produce a satisfactory result
—Java JavaScript programs are written
in Java JavaScript, not Go.”