SlideShare a Scribd company logo
Introduction to Go
a tutorial for developers

Hello! While you’re sitting down, please make	

sure your Go environment is set up.	

!

Grab a USB stick that’s floating around and copy	

the gostick directory somewhere local.	

!

Then read the included README please!
Autobiography
•

Mark Smith <mark@qq.is> @zorkian	


•

Site Reliability Engineer at Dropbox	


•

Contributes to Dreamwidth Studios	


•

github.com/xb95
Today’s Plan
•

What is Go? Where does it fit?	


•

Obligatory Hello World	


•

Contrived example program	


•

Anti-unicorns	


•

Wrap-up
Go in a Nutshell
•

Designed for building systems	


•

Statically compiled, garbage collected	


•

Static typing (w/some duck typing)	


•

Built-in maps (dicts) and strings

Recommended for you

Release with confidence
Release with confidenceRelease with confidence
Release with confidence

This document discusses integrating test automation and code coverage for web service applications. It introduces Postman for calling web services and testing responses, and Jenkins for build automation and tracking test results over time. It then demonstrates setting up a test automation workflow using these tools on a sample Laravel application, including starting and stopping coverage collection, running tests from Postman and PHPUnit, and merging the results. Some best practices and philosophies around test automation and code coverage are also discussed.

jenkinscode coveragephp
X-Debug in Php Storm
X-Debug in Php StormX-Debug in Php Storm
X-Debug in Php Storm

XDebug is a PHP extension that provides debugging and profiling capabilities. It allows you to set breakpoints and pause script execution, avoiding the need to add print/echo statements for debugging. XDebug works with IDEs like PHPStorm, Sublime Text, and Vim. The document provides instructions for installing XDebug on Ubuntu, Mac, and Windows systems, and configuring it to work with PHPStorm or Sublime Text. It also describes various debugging tools available in the IDEs like breakpoints, stepping, and viewing variables.

how to use fiddler (Ver eng)
how to use fiddler (Ver eng)how to use fiddler (Ver eng)
how to use fiddler (Ver eng)

"How to use fiddler" This presentation will be help you, if you first user about fiddler. Some presentation's page has gammer error then, Please, Email me with feedback, i will fix it quickly. Thanks for your watching writter's email : dydwls121200@gmail.com I'm a student in korea. Exactly There are lots of grammer error. .

captureprotocolweb
Go in a Nutshell
•

Multi-core support	


•

Concurrency primitives	


•

Closures, etc. etc.	


•

“Somewhere between C and Python”
The Go Way
•

Go is an opinionated language	


•

gofmt, mixedCaps, capitalization for privacy…	


•

Simple is better than complex	


•

The compiler should help with the heavy lifting
Hello World
Hello World
package main
!

import "fmt"
!

func main() {
fmt.Println("Hello, LCA 2014!")
}

Recommended for you

Developing cacheable PHP applications - PHPLimburgBE 2018
Developing cacheable PHP applications - PHPLimburgBE 2018Developing cacheable PHP applications - PHPLimburgBE 2018
Developing cacheable PHP applications - PHPLimburgBE 2018

In this presentation, I show the audience how to implement HTTP caching best practices in a non-intrusive way in PHP Symfony 4 code base. This presentation focuses on topics like: - Caching using cache-control headers - Cache variations using the Vary header - Conditional requests using headers like ETag & If-None-Match - ESI discovery & parsing using headers like Surrogate-Capability & Surrogate-Control - Caching stateful content using JSON Web Token Validation in Varnish More information about this presentation is available at https://feryn.eu/speaking/developing-cacheable-php-applications-php-limburg-be/

cachingcachehttp
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)

WebSockets couples the performance and flexibility of TCP with the reach of HTTP Prediction: WebSockets will replace simple TCP as preferred underlying protocol. To see how Websockets are used in a popular HTML5-based remote access solution, by visiting the following URL: http://j.mp/1luquBQ

websocketscommunication protocolweb security
Developing cacheable PHP applications - Confoo 2018
Developing cacheable PHP applications - Confoo 2018Developing cacheable PHP applications - Confoo 2018
Developing cacheable PHP applications - Confoo 2018

The document discusses developing cacheable PHP applications. It recommends designing software with HTTP caching in mind by making applications stateless, using well-defined time to lives for cache expiration, and conditionally caching content. It also discusses common problems like time to live variations and authentication that make caching challenging. The document provides examples of implementing caching using Symfony, Twig templates, and Edge Side Includes to break pages into cacheable components.

cachingphpsymfony
Hello World
package main
!

import "fmt"
!

func main() {
fmt.Println("Hello, LCA 2014!")
}
Hello World
package main
!

import "fmt"
!

func main() {
fmt.Println("Hello, LCA 2014!")
}
Hello World
package main
!

import "fmt"
!

func main() {
fmt.Println("Hello, LCA 2014!")
}
Hello World
package main
!

import "fmt"
!

func main() {
fmt.Println("Hello, LCA 2014!")
}

Recommended for you

Beyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisBeyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic Analysis

Despite advances in software design and static analysis techniques, software remains incredibly complicated and difficult to reason about. Understanding highly-concurrent, kernel-level, and intentionally-obfuscated programs are among the problem domains that spawned the field of dynamic program analysis. More than mere debuggers, the challenge of dynamic analysis tools is to be able record, analyze, and replay execution without sacrificing performance. This talk will provide an introduction to the dynamic analysis research space and hopefully inspire you to consider integrating these techniques into your own internal tools.

software testingopen source softwaredynamic content
WebSockets with Spring 4
WebSockets with Spring 4WebSockets with Spring 4
WebSockets with Spring 4

This document discusses WebSockets and Spring WebSockets. It begins by introducing WebSockets as a protocol for real-time full duplex communication over a single TCP connection. It then covers the WebSocket handshake process and JavaScript WebSocket API. Next, it discusses Java WebSocket implementations and how Spring 4 supports WebSockets and the fallback SockJS protocol. Finally, it introduces STOMP as a simple messaging protocol that can be used over WebSockets, and how Spring supports asynchronous messaging using STOMP over WebSockets.

springsockjsstomp
Angular2 ecosystem
Angular2 ecosystemAngular2 ecosystem
Angular2 ecosystem

Jspm is a package manager that supports npm, GitHub registries and extends package.json, allowing installation of packages like jquery, materialize-css and immutablejs using commands like jspm install. It uses SystemJS as its module loader and supports TypeScript, enabling development of Angular 2 applications with features such as components, services and routing. The document provides an overview of the Angular 2 ecosystem including jspm, SystemJS, TypeScript and highlights of the Angular 2 framework.

javascriptjspmangular2
Building Hello World
# Do this in your gostick/ copy
# You did follow the README? :-)
cd helloworld/
go build
./helloworld
Getting Real
•

Go is particularly suited for network services	


•

The standard library is fairly comprehensive	


•

Let’s build an echo server!
Echo Server
1. Listen on port for TCP connections	

2. Accept connections	

3. Read text from connection	

4. Write it back to connection
Standard Library
•

Go has a decent standard library	


•

The ecosystem is still fairly young, so it has some
holes and some things aren’t well optimized	


•

Well built for network services	


•

http://golang.org/pkg/

Recommended for you

Web sockets in Java
Web sockets in JavaWeb sockets in Java
Web sockets in Java

The document discusses WebSocket in Java, including: 1. WebSocket is a protocol providing full-duplex communications over a single TCP connection and was standardized by IETF as RFC 6455. 2. Sample WebSocket applications are demonstrated using the JavaWebSocket library, Java EE 7 with Tomcat, and Spring 4 with SockJS for fallback support to older browsers. 3. Code snippets show how to set up WebSocket servers and handlers in each approach to handle connections, messages, and disconnections from clients.

javaspringjavaee
Optimising Your Front End Workflow With Symfony, Twig, Bower and Gulp
Optimising Your Front End Workflow With Symfony, Twig, Bower and GulpOptimising Your Front End Workflow With Symfony, Twig, Bower and Gulp
Optimising Your Front End Workflow With Symfony, Twig, Bower and Gulp

We take great care in our back end coding workflow, optimising, automating and abstracting as much as is possible. So why don't we do that with our front end code? We'll take a look at some tools to help us take our front end workflow to the next level, and hopefully optimise our load times in the process! We'll be looking at using Twig templates and optimising them for the different areas of your application, integrating Bower and Gulp for managing assets and processing our front-end code to avoid repetitive tasks - looking at how that impacts the typical Symfony workflow.

gulpnpmnode
Xdebug - Your first, last, and best option for troubleshooting PHP code
Xdebug - Your first, last, and best option for troubleshooting PHP codeXdebug - Your first, last, and best option for troubleshooting PHP code
Xdebug - Your first, last, and best option for troubleshooting PHP code

In depth presentation on setting up, configuring, and trigger PHP Xdebug for step through debugging and code profiling. This presentation will not tell you how to configure your Xdebug client. It will help you understand how to configure and tune Xdebug for web and CLI based debugging and profiling in PHP.

profilingdebuggingxdebug
Tip: Searching

When you search the Internet for
information, “Go” is a bad keyword;
everybody uses “golang”.
Echo Server
1. Listen on port for TCP connections
2. Accept connections	

3. Read text from connection	

4. Write it back to connection
Listening for Connections
In the “net” package, you’ll find many useful things, including:
func Listen(net, laddr string) (Listener, error)
Listening for Connections
In the “net” package, you’ll find many useful things, including:
func Listen(net, laddr string) (Listener, error)

package main
!

import "net"
!

func main() {
!

}

Recommended for you

Using Websockets with Play!
Using Websockets with Play!Using Websockets with Play!
Using Websockets with Play!

We use websockets for our clients because we care deeply about a fast, responsive user experience. At the Play! Framework meetup based near us in Mountain View, CA (http://www.meetup.com/PlayFramework/), we presented an introduction to using Websockets with Play!. We cover some relevant background into alternatives, benchmarks, and how Websockets work within Play!.

play frameworkajaxjava
Northeast PHP - High Performance PHP
Northeast PHP - High Performance PHPNortheast PHP - High Performance PHP
Northeast PHP - High Performance PHP

The document is a presentation on high performance PHP. It discusses profiling PHP applications to identify bottlenecks, code-level optimizations that can provide gains, and big wins like upgrading PHP versions and using APC correctly. It also covers load testing tools like JMeter and key takeaways like focusing on big wins and caching.

phpweb performanceweb design and development
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning
PyCon US 2012 - Web Server Bottlenecks and Performance TuningPyCon US 2012 - Web Server Bottlenecks and Performance Tuning
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning

The document discusses web server performance bottlenecks and tuning. It notes that the majority of end-user response time is spent on the frontend. It then examines factors that affect web server performance like memory usage, processes vs threads, client impacts, and application requirements. Specific techniques are suggested for improving performance like using processes over threads, isolating slow clients with Nginx, preloading applications, and monitoring servers.

wsgipythonnew relic
Listening for Connections
In the “net” package, you’ll find many useful things, including:
func Listen(net, laddr string) (Listener, error)

package main
!

import "net"
!

func main() {
... := net.Listen("tcp", ":9000")
}
Variable Definition
•

Go has two ways of declaring variables, explicit and implicit	


•

Explicit:

var foobar uint64	


•

Implicit (type is inferred automatically):

foobar := thingThatReturnsUint64()	


•

Go strives to save on typing redundant information that
the compiler can figure out
Error Handling
•

Using multiple return values to get errors	


•

Idiomatically, you will write this a lot:



results, err := pkg.DoSomething(1, 2)

if err != nil {

log.Fatalf(“Failed: %s”, err)

}

// carry on and use results	


•

Yes, this gets very verbose… oh well
Echo Server
1. Listen on port for TCP connections	

2. Accept connections
3. Read text from connection	

4. Write it back to connection

Recommended for you

Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.

This document discusses using an HTTP proxy to load specific web pages for testing purposes. It explains that many web pages contain resources from multiple domains that cannot be saved locally. An HTTP proxy can be used to intercept requests and redirect local URLs to a test server, while passing through external URLs to the actual web server. The document provides code examples for setting up an HTTP proxy using HTTP::Proxy and modifying the LWP user agent to handle local and remote URLs differently. Using this approach allows a test loop to load repeatable web page content from both local and external sources.

perl web proxy object repeatable testing
WebPagetest - Good, Bad & Ugly
WebPagetest - Good, Bad & UglyWebPagetest - Good, Bad & Ugly
WebPagetest - Good, Bad & Ugly

Presentation by @aaronpeters at Dutch Web Performance Meetup on August 22 2012. The presentation covers new stuff in WPT UI, the WPT API, scripting and hidden gems. Awesome tool, but also room for improvement.

web performance
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about go

Go is an exciting new programming language developed at Google that focuses on high performance and easing the developer experience. It has many advantages over other languages like C++ such as having a simple, quick to learn syntax, extremely fast compiler and execution speeds, powerful standard library, easy concurrency with goroutines and channels, and implicit interfaces. While still missing some features like a full IDE, Go shows great promise for building scalable server side applications and performing data processing.

golanggoogle goprogramming
Connection Pump
func Accept() (Conn, error)
func main() {
listener, err := net.Listen("tcp", ":9000")
!
!
!
!
!
!
!
!
!
!
!
}
Connection Pump
func Accept() (Conn, error)
func main() {
listener, err := net.Listen("tcp", ":9000")
if err != nil {
panic(err)
}
!
!
!
!
!
!
!
!
}
Connection Pump
func Accept() (Conn, error)
func main() {
listener, err := net.Listen("tcp", ":9000")
if err != nil {
panic(err)
}
!
for {

!
!
!
!
}
}
Connection Pump
func Accept() (Conn, error)
func main() {
listener, err := net.Listen("tcp", ":9000")
if err != nil {
panic(err)
}
!
for {
client, err := listener.Accept()
!
!
!
!
}
}

Recommended for you

How to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking NeedsHow to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking Needs

Watch this Tech Talk: https://do.co/video_singuva Highlights from Sneha Inguva’s networking journey through Go. Sneha discusses the useful packages, key learnings, and struggles faced while building a variety of networking services within and outside of DigitalOcean. Walk away with a clear understanding of how to specifically leverage Go for your own networking needs. About the Presenter Sneha Inguva is a Software Engineer on the Networking team at DigitalOcean. She enjoys building cloud products by day and debugging ominous context-canceled errors by night. In her spare time, she professionally lounges around with her cat. New to DigitalOcean? Get US $100 in credit when you sign up: https://do.co/deploytoday To learn more about DigitalOcean: https://www.digitalocean.com/ Follow us on Twitter: https://twitter.com/digitalocean Like us on Facebook: https://www.facebook.com/DigitalOcean Follow us on Instagram: https://www.instagram.com/thedigitalocean/ We're hiring: http://do.co/careers

gonetworkingdigitalocean
Highly concurrent yet natural programming
Highly concurrent yet natural programmingHighly concurrent yet natural programming
Highly concurrent yet natural programming

Infinit's reactor C++ framework allows developers to program in a natural way without having to deal with complex thread-based flows that decrease maintainability and efficiency.

programmingconcurrencysimple
An Introduction to Go
An Introduction to GoAn Introduction to Go
An Introduction to Go

This document summarizes the Go programming language. It was created by Google in 2007 and announced in 2009. Go is intended for systems programming and features garbage collection, static typing, and built-in concurrency with goroutines and channels. It aims to have high compilation speed and a syntax familiar to C/C++/Java programmers. Concurrency in Go is based on lightweight goroutines and channel-based communication between them.

jgccloudflarego (programming language)
Connection Pump
func Accept() (Conn, error)
func main() {
listener, err := net.Listen("tcp", ":9000")
if err != nil {
panic(err)
}
!
for {
client, err := listener.Accept()
if err != nil {
continue
}
!
}
}
Connection Pump
func Accept() (Conn, error)
func main() {
listener, err := net.Listen("tcp", ":9000")
if err != nil {
panic(err)
}
!
for {
client, err := listener.Accept()
if err != nil {
continue
}
handleClient(client)
}
}
Echo Server
1. Listen on port for TCP connections	

2. Accept connections	

3. Read text from connection
4. Write it back to connection
Client Handler
func Read(b []byte) (int, error)
func handleClient(client net.Conn) {
for {
// read from our client
// write it back to our client
}
}

Recommended for you

Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals

This document provides an overview of the Tornado web server and summarizes its internals. It begins with an introduction to Tornado, describing it as a scalable, non-blocking web server and framework written in Python. It then outlines the main Tornado modules and discusses sockets, I/O monitoring using select, poll and epoll, and how Tornado sets up its server loop and handles requests.

tcpweb serverepoll
Node.js for Rubists
Node.js for RubistsNode.js for Rubists
Node.js for Rubists

Node.js is an asynchronous I/O library for JavaScript that aims to provide an easy way to build scalable network programs. It keeps slow operations from blocking other operations through non-blocking I/O and by utilizing a single-threaded event loop model. This allows Node.js applications to handle a large number of concurrent connections using a single process, without the overhead of threads. CommonJS modules provide portability for JavaScript libraries between Node.js and other environments like browsers.

node.jsnoderuby on rails
Go from a PHP Perspective
Go from a PHP PerspectiveGo from a PHP Perspective
Go from a PHP Perspective

A presentation I recently gave at UpstatePHP looking at Google's Go (Golang) from the perspective of PHP developers.

phpgolangruby
Client Handler
func Read(b []byte) (int, error)
func handleClient(client net.Conn) {
for {
// read from our client
// write it back to our client
}
}

Okay, so what’s a []byte?
Primitive Go Types
•

All of the usual suspects (ints, uints, floats)	


•

Built-in string type (Unicode, immutable)	


•

int and uint are architecture-width	


•

byte is just a synonym for uint8
More Types
•

arrays: of a declared, fixed length	


•

slice: a segment (“slice”) of an array	


•

map: key/value storage	


•

pointer: much like C (uses & and *)	


•

(more to come later)
So, []byte…
•

Let’s make an array of bytes:

var ary [4096]byte	


•

What if we don’t know the size? Or don’t care?
Slices solve this problem:

var aryslice []byte

•

This is great, but what is it?

Recommended for you

Apache Thrift
Apache ThriftApache Thrift
Apache Thrift

Thrift is a software framework that allows for efficient cross-language communication. It provides features such as RPC, code generation, and serialization to make it easy to define and develop services that can be used across multiple languages. Supported languages include C++, Java, Python, PHP and more. Thrift handles low-level details like data serialization while providing an interface definition language to define services and data structures.

thrift
Introduction to Thrift
Introduction to ThriftIntroduction to Thrift
Introduction to Thrift

Apache Thrift is a framework for defining and implementing service interfaces and generating code to facilitate remote procedure calls across multiple languages. It handles networking, serialization, and other low-level details, allowing developers to focus on implementing service logic. Services are defined using an interface definition language (IDL) that specifies data types, service methods, and exceptions. The Thrift compiler then generates code to implement clients and servers for the defined services in various languages. On the server side, developers implement handlers that define the logic for each service method. The generated code provides a simple way to deploy the service by connecting the various networking and serialization layers. Many large companies use Thrift for building scalable distributed systems across multiple languages and platforms.

thriftopen sourceapache
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthrough

Slices Explained
var a [16]byte is
Slices Explained
var a [16]byte is
a[3] is
Slices Explained
var a [16]byte is
a[3] is
a[6:8] is
Slices Explained
var a [16]byte is
a[3] is
a[6:8] is
var s []byte is nothing to start with.

Recommended for you

Monitoring and Debugging your Live Applications
Monitoring and Debugging your Live ApplicationsMonitoring and Debugging your Live Applications
Monitoring and Debugging your Live Applications

Some ideas about debugging and monitoring live applications: logging, remote-shells using Twisted (even in non-twisted apps), python debuggers, and creating IM bots so your apps can talk to you. Presented at Kiwi Pycon 2009

kiwipyconremote-shellbots
Streaming 101: Hello World
Streaming 101:  Hello WorldStreaming 101:  Hello World
Streaming 101: Hello World

This talk gave a brief overview of streaming systems, how they different from other data processing systems and typical use cases.

streamingbig datalearning
About Clack
About ClackAbout Clack
About Clack

This is a presentation for International Lisp Conference 2012 which was held in Kyoto, Japan. Clack is a web application environment for Common Lisp to make your web applications be portable and reusable by abstracting HTTP into a simple API. In this paper, I describe what are problems in web development and how Clack solves them.

ilc2012common lispweb application
Slices Explained
var a [16]byte is
a[3] is
a[6:8] is
var s []byte is nothing to start with.
s = a[6:8]; s is
Slices Explained
var a [16]byte is
a[3] is
a[6:8] is
var s []byte is nothing to start with.
s = a[6:8]; s is
s[0] is the same as a[6], etc!

A slice is simply a window into a backing array.
Slices pt. 2
•

Slices are internally a tuple of (array, start, length)	


•

A slice can be moved around (a sliding window)
and resized (limited to the backing array size)	


•

Slices are reference types; great for passing to
functions
Echo Server
1. Listen on port for TCP connections	

2. Accept connections	

3. Read text from connection
4. Write it back to connection

Recommended for you

Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)

Try to imagine the amount of time and effort it would take you to write a bug-free script or application that will accept a URL, port scan it, and for each HTTP service that it finds, it will create a new thread and perform a black box penetration testing while impersonating a Blackberry 9900 smartphone. While you’re thinking, Here’s how you would have done it in Hackersh: “http://localhost” \ -> url \ -> nmap \ -> browse(ua=”Mozilla/5.0 (BlackBerry; U; BlackBerry 9900; en) AppleWebKit/534.11+ (KHTML, like Gecko) Version/7.1.0.346 Mobile Safari/534.11+”) \ -> w3af Meet Hackersh (“Hacker Shell”) – A new, free and open source cross-platform shell (command interpreter) with built-in security commands and Pythonect-like syntax. Aside from being interactive, Hackersh is also scriptable with Pythonect. Pythonect is a new, free, and open source general-purpose dataflow programming language based on Python, written in Python. Hackersh is inspired by Unix pipeline, but takes it a step forward by including built-in features like remote invocation and threads. This 120 minute lab session will introduce Hackersh, the automation gap it fills, and its features. Lots of demonstrations and scripts are included to showcase concepts and ideas.

network securityhackingpythonect
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?

Talk given at DomCode meetup in Utrecht (August 2014) on different frameworks to do asynchronous I/O y Python, with a strong focus on asyncio (PEP-3156).

asynciopython
Java sockets
Java socketsJava sockets
Java sockets

The document discusses keyboard and file access in Java using input streams, readers, and buffers. It then covers socket programming in Java to connect to other computers over a network. A client-server model is described where the client connects to the server, which listens for connections on a port. The server accepts the connection and a separate socket is used to communicate with that client.

Client Handler
func Read(b []byte) (int, error)

func handleClient(client net.Conn) {
for {
!
!
!
!
!
!
}
}
Client Handler
func Read(b []byte) (int, error)

func handleClient(client net.Conn) {
for {
buf := make([]byte, 4096)

!
!
!
!
}
}
Client Handler
func Read(b []byte) (int, error)

func handleClient(client net.Conn) {
for {
buf := make([]byte, 4096)
numbytes, err := client.Read(buf)
!
!
!
!
}
}
Client Handler
func Read(b []byte) (int, error)

func handleClient(client net.Conn) {
for {
buf := make([]byte, 4096)
numbytes, err := client.Read(buf)
if numbytes == 0 || err != nil {
return
}
!
}
}

Recommended for you

Networking and Go: An Engineer's Journey (Strangeloop 2019)
Networking and Go: An Engineer's Journey (Strangeloop 2019)Networking and Go: An Engineer's Journey (Strangeloop 2019)
Networking and Go: An Engineer's Journey (Strangeloop 2019)

My foray into Go began a few years ago when I started working at DigitalOcean. While building an abstraction layer on top of Kubernetes and familiarizing myself with the language, I began to love it. Syntactically simple, with amazing concurrency primitives and a wonderful community, Go was an excellent choice for a cloud-hosting company with a variety of low-level, server-side microservices. In the last year, however, I've joined the software-defined networking team and learned of another application of Go; networking services. The networking team at DigitalOcean uses Go for a variety of purposes - from DHCP servers to IP address management services..to even wrappers around virtual switch tooling. Intrigued, I decided to also investigate how Go could be used to build other services such as port scanners and load-balancers. This session will highlight my networking journey via Go. I will discuss useful packages, key learnings, and even struggles faced while building a variety networking services within and outside of DigitalOcean. I will discuss both relevant packages within the standard library and open source packages used to implement key network protocols. As a result, listeners will gain an understanding of how to specifically leverage Go for their own networking needs.

golangnetworkingmicroservices
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon YangPractical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang

This is a light training/presentation talk. My name is Lyon Yang and I am an IoT hacker. I live in sunny Singapore where IoT is rapidly being deployed – in production. This walkthrough will aim to shed light on the subject of IoT, from finding vulnerabilities in IoT devices to getting shiny hash prompts. Our journey starts with a holistic view of IoT security, the issues faced by IoT devices and the common mistakes made by IoT developers. Things will then get technical as we progress into a both ARM and MIPS exploitation, followed by a ‘hack-along-with-us’ workshop where you will be exploiting a commonly found IoT daemon. If you are new to IoT or a seasoned professional you will likely learn something new in this workshop. https://www.iotvillage.org/#schedule

iot
C101 – Intro to Programming with C
C101 – Intro to Programming with CC101 – Intro to Programming with C
C101 – Intro to Programming with C

The document provides an overview of the C and C++ programming languages. It discusses the history and evolution of C and C++. It describes key features of C like procedural programming, manual memory management, and lack of object orientation. It also describes features of C++ like classes, inheritance, and templates which provide object orientation. The document lists many widely used software written in C/C++ and discusses advantages like speed and compact memory usage and disadvantages like difficulty of manual memory management. It provides examples of basic C code structures and data types.

cc++
Client Handler
func Read(b []byte) (int, error)

func handleClient(client net.Conn) {
for {
buf := make([]byte, 4096)
numbytes, err := client.Read(buf)
if numbytes == 0 || err != nil {
return
}
client.Write(buf)
}
}
Build & Test
# Do this in your gostick/ copy
cd part1/
go build
./part1 &
telnet localhost 9000
# say something and hit enter
More Power
•

The echo server is great, but can only serve one
user at a time!	


•

Concurrent network programming… should we
fork for each child? use a threading library? maybe
we can implement it using non-blocking I/O…	


•

Stop, stop, stop!
Concurrent, Go Style
Remember our main accept loop? Let’s tweak it from this…
func main() {
listener, err := net.Listen("tcp", ":9000")
if err != nil {
panic(err)
}
!
for {
client, err := listener.Accept()
if err != nil {
continue
}
handleClient(client)
}
}

Recommended for you

Servers with Event Machine - David Troy - RailsConf 2011
Servers with Event Machine - David Troy - RailsConf 2011Servers with Event Machine - David Troy - RailsConf 2011
Servers with Event Machine - David Troy - RailsConf 2011

EventMachine allows Ruby programs to handle many concurrent connections without blocking or threads. It uses an asynchronous model where callbacks are invoked in response to I/O events like incoming connections or data. EventMachine provides a high performance non-blocking TCP server that handles all I/O with callbacks rather than blocking. It can be used to build scalable I/O intensive applications like email servers that handle thousands of concurrent connections in a single Ruby process. The key is to never block the EventMachine reactor loop.

david troydave troyeventmachine
From the Inside Out: How Self-Talk Affects Your Community
From the Inside Out: How Self-Talk Affects Your CommunityFrom the Inside Out: How Self-Talk Affects Your Community
From the Inside Out: How Self-Talk Affects Your Community

Identifying and discouraging negative self-talk is a simple thing, but it can have a huge impact on your community in a positive way. It increases self-confidence, improves morale, and generally results in happier, more productive community participants. This, in turn, will make you happy. Negative self-talk is a pervasive, invasive, and unproductive way of thinking. It can trigger a cascade of things, from abandoned patches (“I am not smart/talented/good enough to figure this out”), to withdrawl from the community (“I screwed this up and everyone knows and hates me”), to general discouragement (“I suck, and have nothing valuable to contribute here”). In this talk, I discuss the various methods Dreamwidth and other organizations use to handle negative self-talk, and the best way to deploy those techniques. I also discuss things to keep an eye out for in your community that may be at the root of this type of self-talk, and processes you can go through to eliminate them. Finally, there's a quick overview of impostor syndrome, and the role it plays here.

Chenoweth os bridge 2015 pp
Chenoweth os bridge 2015 ppChenoweth os bridge 2015 pp
Chenoweth os bridge 2015 pp

DNA testing has become the "gold standard" of forensics, but linking an item of evidence to a person of interest isn't always clear cut. New open source tools allow DNA analysts to give statistical weight to evidentiary profiles that were previously unusable, letting juries weigh the evidence for themselves. This talk will discuss the Lab Retriever software package for probabilistic genotyping.

forensic dnaopen sourceforensics
Concurrent, Go Style
…to this!
func main() {
listener, err := net.Listen("tcp", ":9000")
if err != nil {
panic(err)
}
!
for {
client, err := listener.Accept()
if err != nil {
continue
}
go handleClient(client)
}
}
Goroutines
•

A goroutine is a function executing concurrently
with other goroutines	


•

Go multiplexes M goroutines onto N processes,
and scales to 100,000+ goroutines (millions
possible, use case dependent)	


•

N is by default only 1, you can tune it
Goroutines pt. 2
•

Everything in Go is designed to be blocking, in
essence, and the idea is to use goroutines	


•

This makes reasoning about software much easier	


•

Go also provides deadlock detection and
backtraces all living goroutines
Echo v2.0, “Chat”
•

Let’s make a chat server out of our echo server	


•

Design goal: any text from one client is echoed
immediately to all connected clients	


•

Well, clearly, our goroutines have to communicate

Recommended for you

How We Learned To Stop Worrying And Love (or at least live with) GitHub
How We Learned To Stop Worrying And Love (or at least live with) GitHubHow We Learned To Stop Worrying And Love (or at least live with) GitHub
How We Learned To Stop Worrying And Love (or at least live with) GitHub

When Dreamwidth made its public debut in 2009, our code base was housed in a self-hosted Mercurial repository, and we used Bugzilla to track issues and feature requests. In 2012, we switched over to using GitHub for our code repository, but continued to use Bugzilla instead of GitHub’s issue tracker. There were a few reasons we were reluctant to switch: We needed to be open to drop-in contributors. Most of our submissions come from Dreamwidth users who are making their first open source contributions. GitHub is geared more toward full-time contributors who work on multiple projects. Bugzilla provided greater flexibility. It was relatively straightforward to customize our installation with the various fields, tags, and labels that worked best for our workflow and made searching for related items easier. Some of our open issues needed to be kept private for security reasons, and only made visible to a small group of trusted developers. Bugzilla made that as easy as selecting a checkbox. But on one fateful day in early 2014, disaster struck: the virtual server that housed our Bugzilla database was deleted, with no backups. Since we were being forced to start over from scratch with our issue tracker, and because our code was already on GitHub, it made sense to move the rest of our workflow onto GitHub as well. The major problem we had out of the gate with GitHub’s issue tracker was with permissions. We wanted our users to be able to categorize and assign themselves to open issues without granting them commit access. To solve this problem, we developed an automated monitoring system that would take actions based on the content of comments. During the course of our talk, we will cover the basics of the system we have developed. We believe it will provide a helpful example for other open source projects, especially any projects that might have started with only one or two active contributors and now have a larger team to manage. We’ll also talk about how we addressed the workflow issues that made us reluctant to quit using Bugzilla in the first place.

When your code is nearly old enough to vote
When your code is nearly old enough to voteWhen your code is nearly old enough to vote
When your code is nearly old enough to vote

As time marches on, more and more FLOSS projects are reaching ages that qualify them as 'venerable'. On the one hand, that rich history of constant improvement provides a robust framework upon which to build. On the other hand, that can lead to sections of the code marked "here be dragons" that haven't been touched in this millennium, and the ever-accelerating speed of technology's march can leave you with a balance-sheet of technical debt that would make anyone quail. This talk is a case study of Dreamwidth Studios, forked in 2008 from LiveJournal.com, a project that began in 1999. With a quarter-million lines of legacy Perl, it's been hard to decide what to modernize and what to leave alone. Come hear our successes, our failures, and a few horror stories of disasters we've stumbled into along the way.

Hacking In-Group Bias for Fun and Profit
Hacking In-Group Bias for Fun and ProfitHacking In-Group Bias for Fun and Profit
Hacking In-Group Bias for Fun and Profit

This document discusses how to make open source communities more inclusive by addressing unconscious biases. It introduces concepts from social science research like in-group bias, which is the preferential treatment of one's own group, and out-group homogeneity, which is viewing members of outside groups as more similar than members of one's own group. The document provides action items like explicitly inviting diverse contributors and finding commonalities between groups to reduce biases and intergroup aggression. The overall goal is to use insights from social science to create a safer social space and cultural shift within open source.

Communication
•

The common idiom for communicating between
threads in most languages is shared memory	


•

This kind of work is notoriously racy, error prone,
and hard to implement correctly
Communication in Go
•

“Don’t communicate by sharing memory; share
memory by communicating!”	


•

Enter the concept of channels	


•

A built-in goroutine safe method of passing data
Basic Channel Use
ch := make(chan int)

Create a new channel

ch <- 5

Write to a channel
Read from a channel

i := <-ch

The channel in this example is an unbuffered
channel. Reads block until data is available, writes
block until someone reads. Synchronous.
Buffered Channels
ch := make(chan int, 10)

Create a new channel

ch <- 5

Write to a channel
Read from a channel

i := <-ch

The difference: buffered channels won’t block when
inserting data (unless they’re full).

Recommended for you

Slytherin 101: How to Win Friends and Influence People
Slytherin 101: How to Win Friends and Influence PeopleSlytherin 101: How to Win Friends and Influence People
Slytherin 101: How to Win Friends and Influence People

Do you wish that you were better at getting people to do what you need them to do? Do you keep getting put in charge of things and then get stuck wondering how the heck you're supposed to get things done? Do you keep getting into conflicts with other people because of stuff you've said, and you aren't entirely sure why? Fortunately, Slytherin House has you covered. Come to this talk and learn the basics of how to hack human relationships, using the tools of cunning and ambition to achieve inter-House harmony. As long as you promise not to use these techniques to support the next Dark Lord, of course.

people skillslessons from hogwartscommunity management
Keeping your culture afloat through a tidal wave
Keeping your culture afloat through a tidal waveKeeping your culture afloat through a tidal wave
Keeping your culture afloat through a tidal wave

How do you keep a project’s culture true to its core principles when it’s faced with overwhelming interest? In this talk, Azz and Kat draw from experience as early adopters of the Dreamwidth project, both from observing the founders build the culture they wanted to have, and their contributing roles in encouraging the culture in the face of a sudden surge of interest.

community managementcontributor cultureopen source
User Created Content: Maintain accessibility in content you don't control
User Created Content: Maintain accessibility in content you don't controlUser Created Content: Maintain accessibility in content you don't control
User Created Content: Maintain accessibility in content you don't control

Social Media sites and Learning Management Systems rely on end-users, not web developers, to create the content at the heart of the site. How can we design our interfaces to encourage users to create usable, accessible content? Can we train our users without annoying them or driving them away? What tools can we give them to make it easier for them to create the best content? Whether we have professors using Moodle or Sakai to create coursework for students, or bloggers communicating on Diaspora, identi.ca, or Dreamwidth, we want it to be easy for our users to create content every bit as accessible and usable as we would create ourselves.

Chat Server
•

We have to make three main modifications:	

1. Store a list of connected clients	

2. Get input out of the clients	

3. Write each input back to every client	


•

Note: this implementation is a reduced example, so it’s a
little unsafe in one place :-)
Chat Server
•

We have to make three main modifications:	

1. Store a list of connected clients
2. Get input out of the clients	

3. Write each input back to every client	


•

Note: this implementation is a reduced example, so it’s a
little unsafe in one place :-)
Connected Clients
func main() {
...
!
!
!
for {
client, err := listener.Accept()
if err != nil {
continue
}
!
go handleClient(client)
}
}
Connected Clients
func main() {
...
!
var clients []net.Conn
!
for {
client, err := listener.Accept()
if err != nil {
continue
}
clients = append(clients, client)
go handleClient(client)
}
}

Build a slice of clients
and then append
each new client to
the slice.	

!

The append built-in
handles automatically
allocating and
growing the backing
array as necessary.

Recommended for you

Kicking impostor syndrome in the head
Kicking impostor syndrome in the headKicking impostor syndrome in the head
Kicking impostor syndrome in the head

The extended version of "Kicking Impostor Syndrome In The Head" as delivered at Open Source Bridge '13

impostor syndrome
Care and Feeding of Volunteers
Care and Feeding of VolunteersCare and Feeding of Volunteers
Care and Feeding of Volunteers

Volunteers make open source projects go. This talk discusses how to attract volunteers, what to do once you have, and how to keep them happy once you've got them.

volunteersopen sourcecommunity management
Sowing the Seeds of Diversity
Sowing the Seeds of DiversitySowing the Seeds of Diversity
Sowing the Seeds of Diversity

Mark Smith discusses how to build diverse and inclusive software communities. He explains that Dreamwidth Studios has been successful in attracting a diverse group of contributors, 70% of whom identify as female and 50% are new to programming, by prioritizing people over code. Typical open source projects can lack support for new contributors and tolerance for problematic behaviors. Smith advocates for creating a culture of respect, encouragement, and forgiveness to attract a more diverse group of contributors and foster a healthier community.

Chat Server
•

We have to make three main modifications:	

1. Store a list of connected clients	

2. Get input out of the clients
3. Write each input back to every client	


•

Note: this implementation is a reduced example, so it’s a
little unsafe in one place :-)
Getting Input
func main() {
...

!
for {
...
clients = append(clients, client)
go handleClient(client)
}
}
!
func handleClient(client net.Conn) {
for {
...
client.Write(buf)
}
}
Getting Input
func main() {
...
input := make(chan []byte, 10)
!
for {
...
clients = append(clients, client)
go handleClient(client)
}
}
!
func handleClient(client net.Conn) {
for {
...
client.Write(buf)
}
}
Getting Input
func main() {
...
input := make(chan []byte, 10)
!
for {
...
clients = append(clients, client)
go handleClient(client, input)
}
}
!
func handleClient(client net.Conn) {
for {
...
client.Write(buf)
}
}

Recommended for you

Be Kind To Your Wrists (you’ll miss them when they’re gone)
Be Kind To Your Wrists (you’ll miss them when they’re gone)Be Kind To Your Wrists (you’ll miss them when they’re gone)
Be Kind To Your Wrists (you’ll miss them when they’re gone)

A brief introduction to lowering RSI risk and treating RSI symptoms for programmers, sysadmins, and other people who type too much.

Web Accessibility for the 21st Century
Web Accessibility for the 21st CenturyWeb Accessibility for the 21st Century
Web Accessibility for the 21st Century

You know it's important for your web project to be accessible to people who use all kinds of assistive technology to access the internet. But all the guidelines for web accessibility you can find don't go much beyond "make sure all your images have alt text", and all the resources you can find treat "accessibility" as a synonym for "making your site work in a screen reader". You know there are other things you should be doing and other forms of assistive technology you should be accomodating, but all the best practices documents are a complicated morass of contradicting information (if you can find best practices documents at all.) Have no fear! This tutorial gives you a number of concrete steps to take to make things more accessible. This presentation has downloadable notes and exercises available at http://denise.dreamwidth.org/tag/a11y . Video of the talk should be available later.

accessibility
Servers and Processes: Behavior and Analysis
Servers and Processes: Behavior and AnalysisServers and Processes: Behavior and Analysis
Servers and Processes: Behavior and Analysis

This document provides an overview of servers, processes, and system administration. It discusses servers as machines made up of components like RAM, CPU, and I/O. It then covers these components and their capacities, as well as processes and how they interact with servers through system calls. Hands-on examples are provided to demonstrate monitoring servers and investigating processes using tools like top, lsof, strace, and vmstat.

Getting Input
func main() {
...
input := make(chan []byte, 10)
!
for {
...
clients = append(clients, client)
go handleClient(client, input)
}
}
!
func handleClient(client net.Conn, input chan []byte) {
for {
...
client.Write(buf)
}
}
Getting Input
func main() {
...
input := make(chan []byte, 10)
!
for {
...
clients = append(clients, client)
go handleClient(client, input)
}
}
!
func handleClient(client net.Conn, input chan []byte) {
for {
...
client.Write(buf)
input <- buf
}
}
Getting Input
func main() {
...
input := make(chan []byte, 10)
!
for {
...
clients = append(clients, client)
go handleClient(client, input)
}
}
!
func handleClient(client net.Conn, input chan []byte) {
for {
...
client.Write(buf)
Removed the Write!
input <- buf
}
}
What is Happening?
•

handleClient still is a blocking read loop, but
instead of writing back to the client it writes the
bytes onto a channel	


•

main now has a list of all clients and a channel
that everybody is writing input to	


•

Final piece: somebody to read from the channel!

Recommended for you

Overcoming Impostor Syndrome
Overcoming Impostor SyndromeOvercoming Impostor Syndrome
Overcoming Impostor Syndrome

A 20-minute talk on overcoming impostor syndrome -- the persistent feeling that you're not qualified to be doing whatever you're doing, and everyone's going to find out you're a fake any minute now.

Build Your Own Contributors, One Part At A Time
Build Your Own Contributors, One Part At A TimeBuild Your Own Contributors, One Part At A Time
Build Your Own Contributors, One Part At A Time

Dreamwidth Studios, a code fork of the LiveJournal open source blogging software, averages 50 commits a week from over 65 unique contributors. Over half of those contributors have either never programmed in Perl or never contributed to an Open Source project before, and roughly 75% of those contributors are women. Mark Smith and Denise Paolucci, owners of Dreamwidth Studios, discuss the tactics they've used to make their project successful, and how other projects can implement the same.

mentoringopen sourcecommunity
Choose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presenceChoose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presence

Our Linux Web Hosting plans offer unbeatable performance, security, and scalability, ensuring your website runs smoothly and efficiently. Visit- https://onliveserver.com/linux-web-hosting/

cheap linux hosting
Chat Server
•

We have to make three main modifications:	

1. Store a list of connected clients	

2. Get input out of the clients	

3. Write each input back to every client

•

Note: this implementation is a reduced example, so it’s a
little unsafe in one place :-)
The Chat Manager
func main() {
...
var clients []net.Conn
input := make(chan []byte, 10)
!
!
!
!
We’ve
!
!
!
!
...
}

seen this all before…
The Chat Manager
func main() {
...
var clients []net.Conn
input := make(chan []byte, 10)
go func() {

!
!
!
!
!
}()
...
}

You can create goroutines
out of closures, too.	

!
The Chat Manager
!
func main() {
...
var clients []net.Conn
input := make(chan []byte, 10)
go func() {
for {
message := <-input

!
!
}
}()
...
}

!
!

This is all blocking!

Recommended for you

Measuring the Impact of Network Latency at Twitter
Measuring the Impact of Network Latency at TwitterMeasuring the Impact of Network Latency at Twitter
Measuring the Impact of Network Latency at Twitter

Widya Salim and Victor Ma will outline the causal impact analysis, framework, and key learnings used to quantify the impact of reducing Twitter's network latency.

Advanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly DetectionAdvanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly Detection

Cybersecurity is a major concern in today's connected digital world. Threats to organizations are constantly evolving and have the potential to compromise sensitive information, disrupt operations, and lead to significant financial losses. Traditional cybersecurity techniques often fall short against modern attackers. Therefore, advanced techniques for cyber security analysis and anomaly detection are essential for protecting digital assets. This blog explores these cutting-edge methods, providing a comprehensive overview of their application and importance.

cybersecurityanomaly detectionadvanced techniques
Best Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdfBest Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdf

As a popular open-source library for analytics engineering, dbt is often used in combination with Airflow. Orchestrating and executing dbt models as DAGs ensures an additional layer of control over tasks, observability, and provides a reliable, scalable environment to run dbt models. This webinar will cover a step-by-step guide to Cosmos, an open source package from Astronomer that helps you easily run your dbt Core projects as Airflow DAGs and Task Groups, all with just a few lines of code. We’ll walk through: - Standard ways of running dbt (and when to utilize other methods) - How Cosmos can be used to run and visualize your dbt projects in Airflow - Common challenges and how to address them, including performance, dependency conflicts, and more - How running dbt projects in Airflow helps with cost optimization Webinar given on 9 July 2024

apache airflowdbtdbt-core
The Chat Manager
!
func main() {
...
var clients []net.Conn
This
input := make(chan []byte, 10)
go func() {
for {
message := <-input
for _, client := range clients {
!
}
}
}()
...
}

!
!

is all blocking!
range and _
for _, client := range clients {..}

•

The range keyword iterates over maps/slices/
arrays and returns the key (or index) and value	


•

Underscore (_) is the anonymous variable (“blank
identifier”), you can use it to discard results
The Chat Manager
func main() {
...
var clients []net.Conn
input := make(chan []byte, 10)
go func() {
for {
message := <-input
for _, client := range clients {
client.Write(message)
}
}
}()
...
}
Build & Test
# Do this in your gostick/ copy
cd part2/
go build
./part2 &
telnet localhost 9000
# say something and hit enter, now connect
# again in another window and chat! :-)

Recommended for you

Cookies program to display the information though cookie creation
Cookies program to display the information though cookie creationCookies program to display the information though cookie creation
Cookies program to display the information though cookie creation

Java Servlet programs

Quantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLMQuantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLM

Quantum Communications Q&A with Gemini LLM. These are based on Shannon's Noisy channel Theorem and offers how the classical theory applies to the quantum world.

quantum communicationsshannon's channel theoremclassical theory
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf

In the modern digital era, social media platforms have become integral to our daily lives. These platforms, including Facebook, Instagram, WhatsApp, and Snapchat, offer countless ways to connect, share, and communicate.

social media hackerfacebook hackerhire a instagram hacker
Echo 3.0, “Frotzer”
•

We’re entering the land of extremely contrived
tutorial examples, but…	


•

Let’s give our chat server some behaviors!	


•

When a user chats, we apply some formatting
rules before sending it out to other users
But First: More Type Talk!
•

Go doesn’t have classes (or objects, really)	


•

However, you have named types, and methods are
attached to named types:










type Uppercaser struct{}
!
func (self Uppercaser) Frotz(input []byte) []byte {
return bytes.ToUpper(input)
}
Um, struct{}?
•

Go supports structs, very much like any other
language that has structs	


•

The empty struct is often used for hanging methods	


•

Instantiating a struct type:

foobar := Lowercaser{}

foobar.Frotz(“HELLO”) // “hello”
Interfaces
•

In Go, an interface specifies a collection of
methods attached to a name	


•

Interfaces are implicit (duck typed)











type Frotzer interface {
Frotz([]byte) []byte
}
!
type Uppercaser struct{}
func (self Uppercaser) Frotz(input []byte) []byte {
return bytes.ToUpper(input)
}

Recommended for you

How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx

Revolutionize your transportation processes with our cutting-edge RPA software. Automate repetitive tasks, reduce costs, and enhance efficiency in the logistics sector with our advanced solutions.

rpa in transportationrpa in transportation industryrpa in transportation sector
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...

Jindong Gu, Zhen Han, Shuo Chen, Ahmad Beirami, Bailan He, Gengyuan Zhang, Ruotong Liao, Yao Qin, Volker Tresp, Philip Torr "A Systematic Survey of Prompt Engineering on Vision-Language Foundation Models" arXiv2023 https://arxiv.org/abs/2307.12980

The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses

CIO Council Cal Poly Humboldt September 22, 2023

national research platformdistributed supercomputerdistributed systems
Implementing Frotzing
func chatManager(clients *[]net.Conn, input chan []byte
) {
for {
message := <-input
for _, client := range *clients {
client.Write(message)
}
}
}

This is the input handler loop we built a few minutes ago,
except now we pulled it out of main and made it a
function.
Implementing Frotzing
func chatManager(clients *[]net.Conn, input chan []byte,
frotz Frotzer) {
for {
message := <-input
for _, client := range *clients {
client.Write(frotz.Frotz(message))
}
}
}

Now it takes a third argument: an interface. Any type that
implements Frotzer can be used!
Making Frotzers
These are both named types, and both implement
(implicitly!) the Frotzer interface. Thanks, compiler!
type Uppercaser struct{}
func (self Uppercaser) Frotz(input []byte) []byte {
return bytes.ToUpper(input)
}
!
type Lowercaser struct{}
func (self Lowercaser) Frotz(input []byte) []byte {
return bytes.ToLower(input)
}
A New Main
func main() {
...
var clients []net.Conn
input := make(chan []byte, 10)
go chatManager(&clients, input)
!
!
for {
client, err := listener.Accept()
if err != nil {
continue
}
clients = append(clients, client)
go handleClient(client, input)
}
}

Recommended for you

Calgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptxCalgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptx

MuleSoft Meetup on APM and IDP

mulesoftai
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...

This presentation explores the practical application of image description techniques. Familiar guidelines will be demonstrated in practice, and descriptions will be developed “live”! If you have learned a lot about the theory of image description techniques but want to feel more confident putting them into practice, this is the presentation for you. There will be useful, actionable information for everyone, whether you are working with authors, colleagues, alone, or leveraging AI as a collaborator. Link to presentation recording and slides: https://bnctechforum.ca/sessions/details-of-description-part-ii-describing-images-in-practice/ Presented by BookNet Canada on June 25, 2024, with support from the Department of Canadian Heritage.

a11yaccessibilityalt text
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world

The presentation showcases the diverse real-world applications of Fused Deposition Modeling (FDM) across multiple industries: 1. **Manufacturing**: FDM is utilized in manufacturing for rapid prototyping, creating custom tools and fixtures, and producing functional end-use parts. Companies leverage its cost-effectiveness and flexibility to streamline production processes. 2. **Medical**: In the medical field, FDM is used to create patient-specific anatomical models, surgical guides, and prosthetics. Its ability to produce precise and biocompatible parts supports advancements in personalized healthcare solutions. 3. **Education**: FDM plays a crucial role in education by enabling students to learn about design and engineering through hands-on 3D printing projects. It promotes innovation and practical skill development in STEM disciplines. 4. **Science**: Researchers use FDM to prototype equipment for scientific experiments, build custom laboratory tools, and create models for visualization and testing purposes. It facilitates rapid iteration and customization in scientific endeavors. 5. **Automotive**: Automotive manufacturers employ FDM for prototyping vehicle components, tooling for assembly lines, and customized parts. It speeds up the design validation process and enhances efficiency in automotive engineering. 6. **Consumer Electronics**: FDM is utilized in consumer electronics for designing and prototyping product enclosures, casings, and internal components. It enables rapid iteration and customization to meet evolving consumer demands. 7. **Robotics**: Robotics engineers leverage FDM to prototype robot parts, create lightweight and durable components, and customize robot designs for specific applications. It supports innovation and optimization in robotic systems. 8. **Aerospace**: In aerospace, FDM is used to manufacture lightweight parts, complex geometries, and prototypes of aircraft components. It contributes to cost reduction, faster production cycles, and weight savings in aerospace engineering. 9. **Architecture**: Architects utilize FDM for creating detailed architectural models, prototypes of building components, and intricate designs. It aids in visualizing concepts, testing structural integrity, and communicating design ideas effectively. Each industry example demonstrates how FDM enhances innovation, accelerates product development, and addresses specific challenges through advanced manufacturing capabilities.

fdmffffused deposition modeling
A New Main
func main() {
...
var clients []net.Conn
input := make(chan []byte, 10)
go chatManager(&clients, input, Lowercaser{})
go chatManager(&clients, input, Uppercaser{})
!
for {
client, err := listener.Accept()
if err != nil {
continue
}
clients = append(clients, client)
go handleClient(client, input)
}
}
A New Main pt. 2
•

The chatManager functions are spawned into
separate goroutines	


•

Channels are goroutine safe, so they end up
interleaving reads (not guaranteed!)	


•

chatManager doesn’t know what you’re passing it
as a Frotzer, it just knows it can call Frotz on it
Build & Test
# Do this in your gostick/ copy
cd part3/
go build
./part3 &
telnet localhost 9000
# say something and hit enter, your text
# should alternate UPPER/lower
Review
•

A multi-user chat server demonstrating many core
parts of the Go programming language	


•

Built-in concurrency that is easy to use and trivially
allows relatively powerful constructions	


•

A classless, statically type system that still enables
many OO concepts

Recommended for you

BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALLBLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL

Blockchain technology is transforming industries and reshaping the way we conduct business, manage data, and secure transactions. Whether you're new to blockchain or looking to deepen your knowledge, our guidebook, "Blockchain for Dummies", is your ultimate resource.

blockchainweb3blockchain technology
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In

Six months into 2024, and it is clear the privacy ecosystem takes no days off!! Regulators continue to implement and enforce new regulations, businesses strive to meet requirements, and technology advances like AI have privacy professionals scratching their heads about managing risk. What can we learn about the first six months of data privacy trends and events in 2024? How should this inform your privacy program management for the rest of the year? Join TrustArc, Goodwin, and Snyk privacy experts as they discuss the changes we’ve seen in the first half of 2024 and gain insight into the concrete, actionable steps you can take to up-level your privacy program in the second half of the year. This webinar will review: - Key changes to privacy regulations in 2024 - Key themes in privacy and data governance in 2024 - How to maximize your privacy program in the second half of 2024

data privacyprivacy complianceai
The Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive ComputingThe Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive Computing

Invited Remote Lecture to SC21 The International Conference for High Performance Computing, Networking, Storage, and Analysis St. Louis, Missouri November 18, 2021

distributed supercomputerdistributed machine learning
Go is Awesome :-)

This slide should have unicorns and bunnies on it
Things That Aren’t Unicorns Yet
•

The GC is generally pretty solid, but if you are
doing many allocations and need performance, you
have to do the usual tricks	


•

Standard library is pretty young and not optimized	


•

Overall ecosystem is small (but growing, hi!)
Also: The Scheduler
•

It’s new and has room for improvement	


•

Heavy use of channels between goroutines is
probably faster in one process	


•

You’ll have to play with GOMAXPROCS and
understand your application
Topics Undiscussed
•

Building your own packages (it’s easy)	


•

Importing from external repositories

import pcap “github.com/akrennmair/gopcap”	


•

Using gofmt (do it!)	


•

switch, select, etc.	


•

Type assertions, reflection, even more etc.

Recommended for you

[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf

Kief Morris rethinks the infrastructure code delivery lifecycle, advocating for a shift towards composable infrastructure systems. We should shift to designing around deployable components rather than code modules, use more useful levels of abstraction, and drive design and deployment from applications rather than bottom-up, monolithic architecture and delivery.

infrastructure as codeclouddevops
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx

How do we build an IoT product, and make it profitable? Talk from the IoT meetup in March 2024. https://www.meetup.com/iot-sweden/events/299487375/

iot
Manual | Product | Research Presentation
Manual | Product | Research PresentationManual | Product | Research Presentation
Manual | Product | Research Presentation

Manual Method of Product Research | Helium10 | MBS RETRIEVER

product researchhelium10 | mbs retriever
Thank you!

Mark Smith <mark@qq.is> @zorkian

SRE at Dropbox (we’re hiring!)

•

Some recommended reading:

Effective Go golang.org/doc/effective_go.html

FAQ golang.org/doc/faq	


•

Many more talks and presentations:

code.google.com/p/go-wiki/wiki/GoTalks	


•

The Go Playground! play.golang.org

More Related Content

What's hot

Web::Scraper
Web::ScraperWeb::Scraper
Web::Scraper
Tatsuhiko Miyagawa
 
Dancing with websocket
Dancing with websocketDancing with websocket
Dancing with websocket
Damien Krotkine
 
SDPHP - Percona Toolkit (It's Basically Magic)
SDPHP - Percona Toolkit (It's Basically Magic)SDPHP - Percona Toolkit (It's Basically Magic)
SDPHP - Percona Toolkit (It's Basically Magic)
Robert Swisher
 
Release with confidence
Release with confidenceRelease with confidence
Release with confidence
John Congdon
 
X-Debug in Php Storm
X-Debug in Php StormX-Debug in Php Storm
X-Debug in Php Storm
KLabCyscorpions-TechBlog
 
how to use fiddler (Ver eng)
how to use fiddler (Ver eng)how to use fiddler (Ver eng)
how to use fiddler (Ver eng)
용진 조
 
Developing cacheable PHP applications - PHPLimburgBE 2018
Developing cacheable PHP applications - PHPLimburgBE 2018Developing cacheable PHP applications - PHPLimburgBE 2018
Developing cacheable PHP applications - PHPLimburgBE 2018
Thijs Feryn
 
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
Ericom Software
 
Developing cacheable PHP applications - Confoo 2018
Developing cacheable PHP applications - Confoo 2018Developing cacheable PHP applications - Confoo 2018
Developing cacheable PHP applications - Confoo 2018
Thijs Feryn
 
Beyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisBeyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic Analysis
Fastly
 
WebSockets with Spring 4
WebSockets with Spring 4WebSockets with Spring 4
WebSockets with Spring 4
Sergi Almar i Graupera
 
Angular2 ecosystem
Angular2 ecosystemAngular2 ecosystem
Angular2 ecosystem
Kamil Lelonek
 
Web sockets in Java
Web sockets in JavaWeb sockets in Java
Web sockets in Java
Pance Cavkovski
 
Optimising Your Front End Workflow With Symfony, Twig, Bower and Gulp
Optimising Your Front End Workflow With Symfony, Twig, Bower and GulpOptimising Your Front End Workflow With Symfony, Twig, Bower and Gulp
Optimising Your Front End Workflow With Symfony, Twig, Bower and Gulp
Matthew Davis
 
Xdebug - Your first, last, and best option for troubleshooting PHP code
Xdebug - Your first, last, and best option for troubleshooting PHP codeXdebug - Your first, last, and best option for troubleshooting PHP code
Xdebug - Your first, last, and best option for troubleshooting PHP code
Adam Englander
 
Using Websockets with Play!
Using Websockets with Play!Using Websockets with Play!
Using Websockets with Play!
Andrew Conner
 
Northeast PHP - High Performance PHP
Northeast PHP - High Performance PHPNortheast PHP - High Performance PHP
Northeast PHP - High Performance PHP
Jonathan Klein
 
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning
PyCon US 2012 - Web Server Bottlenecks and Performance TuningPyCon US 2012 - Web Server Bottlenecks and Performance Tuning
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning
Graham Dumpleton
 
Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.
Workhorse Computing
 
WebPagetest - Good, Bad & Ugly
WebPagetest - Good, Bad & UglyWebPagetest - Good, Bad & Ugly
WebPagetest - Good, Bad & Ugly
Aaron Peters
 

What's hot (20)

Web::Scraper
Web::ScraperWeb::Scraper
Web::Scraper
 
Dancing with websocket
Dancing with websocketDancing with websocket
Dancing with websocket
 
SDPHP - Percona Toolkit (It's Basically Magic)
SDPHP - Percona Toolkit (It's Basically Magic)SDPHP - Percona Toolkit (It's Basically Magic)
SDPHP - Percona Toolkit (It's Basically Magic)
 
Release with confidence
Release with confidenceRelease with confidence
Release with confidence
 
X-Debug in Php Storm
X-Debug in Php StormX-Debug in Php Storm
X-Debug in Php Storm
 
how to use fiddler (Ver eng)
how to use fiddler (Ver eng)how to use fiddler (Ver eng)
how to use fiddler (Ver eng)
 
Developing cacheable PHP applications - PHPLimburgBE 2018
Developing cacheable PHP applications - PHPLimburgBE 2018Developing cacheable PHP applications - PHPLimburgBE 2018
Developing cacheable PHP applications - PHPLimburgBE 2018
 
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
 
Developing cacheable PHP applications - Confoo 2018
Developing cacheable PHP applications - Confoo 2018Developing cacheable PHP applications - Confoo 2018
Developing cacheable PHP applications - Confoo 2018
 
Beyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisBeyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic Analysis
 
WebSockets with Spring 4
WebSockets with Spring 4WebSockets with Spring 4
WebSockets with Spring 4
 
Angular2 ecosystem
Angular2 ecosystemAngular2 ecosystem
Angular2 ecosystem
 
Web sockets in Java
Web sockets in JavaWeb sockets in Java
Web sockets in Java
 
Optimising Your Front End Workflow With Symfony, Twig, Bower and Gulp
Optimising Your Front End Workflow With Symfony, Twig, Bower and GulpOptimising Your Front End Workflow With Symfony, Twig, Bower and Gulp
Optimising Your Front End Workflow With Symfony, Twig, Bower and Gulp
 
Xdebug - Your first, last, and best option for troubleshooting PHP code
Xdebug - Your first, last, and best option for troubleshooting PHP codeXdebug - Your first, last, and best option for troubleshooting PHP code
Xdebug - Your first, last, and best option for troubleshooting PHP code
 
Using Websockets with Play!
Using Websockets with Play!Using Websockets with Play!
Using Websockets with Play!
 
Northeast PHP - High Performance PHP
Northeast PHP - High Performance PHPNortheast PHP - High Performance PHP
Northeast PHP - High Performance PHP
 
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning
PyCon US 2012 - Web Server Bottlenecks and Performance TuningPyCon US 2012 - Web Server Bottlenecks and Performance Tuning
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning
 
Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.
 
WebPagetest - Good, Bad & Ugly
WebPagetest - Good, Bad & UglyWebPagetest - Good, Bad & Ugly
WebPagetest - Good, Bad & Ugly
 

Similar to LCA2014 - Introduction to Go

10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about go
Dvir Volk
 
How to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking NeedsHow to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking Needs
DigitalOcean
 
Highly concurrent yet natural programming
Highly concurrent yet natural programmingHighly concurrent yet natural programming
Highly concurrent yet natural programming
Infinit
 
An Introduction to Go
An Introduction to GoAn Introduction to Go
An Introduction to Go
Cloudflare
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
Praveen Gollakota
 
Node.js for Rubists
Node.js for RubistsNode.js for Rubists
Node.js for Rubists
Sagiv Ofek
 
Go from a PHP Perspective
Go from a PHP PerspectiveGo from a PHP Perspective
Go from a PHP Perspective
Barry Jones
 
Apache Thrift
Apache ThriftApache Thrift
Apache Thrift
knight1128
 
Introduction to Thrift
Introduction to ThriftIntroduction to Thrift
Introduction to Thrift
Dvir Volk
 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthrough
gabriellekuruvilla
 
Monitoring and Debugging your Live Applications
Monitoring and Debugging your Live ApplicationsMonitoring and Debugging your Live Applications
Monitoring and Debugging your Live Applications
Robert Coup
 
Streaming 101: Hello World
Streaming 101:  Hello WorldStreaming 101:  Hello World
Streaming 101: Hello World
Josh Fischer
 
About Clack
About ClackAbout Clack
About Clack
fukamachi
 
Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)
Itzik Kotler
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
Saúl Ibarra Corretgé
 
Java sockets
Java socketsJava sockets
Java sockets
Stephen Pradeep
 
Networking and Go: An Engineer's Journey (Strangeloop 2019)
Networking and Go: An Engineer's Journey (Strangeloop 2019)Networking and Go: An Engineer's Journey (Strangeloop 2019)
Networking and Go: An Engineer's Journey (Strangeloop 2019)
Sneha Inguva
 
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon YangPractical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Lyon Yang
 
C101 – Intro to Programming with C
C101 – Intro to Programming with CC101 – Intro to Programming with C
C101 – Intro to Programming with C
gpsoft_sk
 
Servers with Event Machine - David Troy - RailsConf 2011
Servers with Event Machine - David Troy - RailsConf 2011Servers with Event Machine - David Troy - RailsConf 2011
Servers with Event Machine - David Troy - RailsConf 2011
David Troy
 

Similar to LCA2014 - Introduction to Go (20)

10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about go
 
How to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking NeedsHow to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking Needs
 
Highly concurrent yet natural programming
Highly concurrent yet natural programmingHighly concurrent yet natural programming
Highly concurrent yet natural programming
 
An Introduction to Go
An Introduction to GoAn Introduction to Go
An Introduction to Go
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
 
Node.js for Rubists
Node.js for RubistsNode.js for Rubists
Node.js for Rubists
 
Go from a PHP Perspective
Go from a PHP PerspectiveGo from a PHP Perspective
Go from a PHP Perspective
 
Apache Thrift
Apache ThriftApache Thrift
Apache Thrift
 
Introduction to Thrift
Introduction to ThriftIntroduction to Thrift
Introduction to Thrift
 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthrough
 
Monitoring and Debugging your Live Applications
Monitoring and Debugging your Live ApplicationsMonitoring and Debugging your Live Applications
Monitoring and Debugging your Live Applications
 
Streaming 101: Hello World
Streaming 101:  Hello WorldStreaming 101:  Hello World
Streaming 101: Hello World
 
About Clack
About ClackAbout Clack
About Clack
 
Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)Hack Like It's 2013 (The Workshop)
Hack Like It's 2013 (The Workshop)
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
 
Java sockets
Java socketsJava sockets
Java sockets
 
Networking and Go: An Engineer's Journey (Strangeloop 2019)
Networking and Go: An Engineer's Journey (Strangeloop 2019)Networking and Go: An Engineer's Journey (Strangeloop 2019)
Networking and Go: An Engineer's Journey (Strangeloop 2019)
 
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon YangPractical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
Practical IoT Exploitation (DEFCON23 IoTVillage) - Lyon Yang
 
C101 – Intro to Programming with C
C101 – Intro to Programming with CC101 – Intro to Programming with C
C101 – Intro to Programming with C
 
Servers with Event Machine - David Troy - RailsConf 2011
Servers with Event Machine - David Troy - RailsConf 2011Servers with Event Machine - David Troy - RailsConf 2011
Servers with Event Machine - David Troy - RailsConf 2011
 

More from dreamwidth

From the Inside Out: How Self-Talk Affects Your Community
From the Inside Out: How Self-Talk Affects Your CommunityFrom the Inside Out: How Self-Talk Affects Your Community
From the Inside Out: How Self-Talk Affects Your Community
dreamwidth
 
Chenoweth os bridge 2015 pp
Chenoweth os bridge 2015 ppChenoweth os bridge 2015 pp
Chenoweth os bridge 2015 pp
dreamwidth
 
How We Learned To Stop Worrying And Love (or at least live with) GitHub
How We Learned To Stop Worrying And Love (or at least live with) GitHubHow We Learned To Stop Worrying And Love (or at least live with) GitHub
How We Learned To Stop Worrying And Love (or at least live with) GitHub
dreamwidth
 
When your code is nearly old enough to vote
When your code is nearly old enough to voteWhen your code is nearly old enough to vote
When your code is nearly old enough to vote
dreamwidth
 
Hacking In-Group Bias for Fun and Profit
Hacking In-Group Bias for Fun and ProfitHacking In-Group Bias for Fun and Profit
Hacking In-Group Bias for Fun and Profit
dreamwidth
 
Slytherin 101: How to Win Friends and Influence People
Slytherin 101: How to Win Friends and Influence PeopleSlytherin 101: How to Win Friends and Influence People
Slytherin 101: How to Win Friends and Influence People
dreamwidth
 
Keeping your culture afloat through a tidal wave
Keeping your culture afloat through a tidal waveKeeping your culture afloat through a tidal wave
Keeping your culture afloat through a tidal wave
dreamwidth
 
User Created Content: Maintain accessibility in content you don't control
User Created Content: Maintain accessibility in content you don't controlUser Created Content: Maintain accessibility in content you don't control
User Created Content: Maintain accessibility in content you don't control
dreamwidth
 
Kicking impostor syndrome in the head
Kicking impostor syndrome in the headKicking impostor syndrome in the head
Kicking impostor syndrome in the head
dreamwidth
 
Care and Feeding of Volunteers
Care and Feeding of VolunteersCare and Feeding of Volunteers
Care and Feeding of Volunteers
dreamwidth
 
Sowing the Seeds of Diversity
Sowing the Seeds of DiversitySowing the Seeds of Diversity
Sowing the Seeds of Diversity
dreamwidth
 
Be Kind To Your Wrists (you’ll miss them when they’re gone)
Be Kind To Your Wrists (you’ll miss them when they’re gone)Be Kind To Your Wrists (you’ll miss them when they’re gone)
Be Kind To Your Wrists (you’ll miss them when they’re gone)
dreamwidth
 
Web Accessibility for the 21st Century
Web Accessibility for the 21st CenturyWeb Accessibility for the 21st Century
Web Accessibility for the 21st Century
dreamwidth
 
Servers and Processes: Behavior and Analysis
Servers and Processes: Behavior and AnalysisServers and Processes: Behavior and Analysis
Servers and Processes: Behavior and Analysis
dreamwidth
 
Overcoming Impostor Syndrome
Overcoming Impostor SyndromeOvercoming Impostor Syndrome
Overcoming Impostor Syndrome
dreamwidth
 
Build Your Own Contributors, One Part At A Time
Build Your Own Contributors, One Part At A TimeBuild Your Own Contributors, One Part At A Time
Build Your Own Contributors, One Part At A Time
dreamwidth
 

More from dreamwidth (16)

From the Inside Out: How Self-Talk Affects Your Community
From the Inside Out: How Self-Talk Affects Your CommunityFrom the Inside Out: How Self-Talk Affects Your Community
From the Inside Out: How Self-Talk Affects Your Community
 
Chenoweth os bridge 2015 pp
Chenoweth os bridge 2015 ppChenoweth os bridge 2015 pp
Chenoweth os bridge 2015 pp
 
How We Learned To Stop Worrying And Love (or at least live with) GitHub
How We Learned To Stop Worrying And Love (or at least live with) GitHubHow We Learned To Stop Worrying And Love (or at least live with) GitHub
How We Learned To Stop Worrying And Love (or at least live with) GitHub
 
When your code is nearly old enough to vote
When your code is nearly old enough to voteWhen your code is nearly old enough to vote
When your code is nearly old enough to vote
 
Hacking In-Group Bias for Fun and Profit
Hacking In-Group Bias for Fun and ProfitHacking In-Group Bias for Fun and Profit
Hacking In-Group Bias for Fun and Profit
 
Slytherin 101: How to Win Friends and Influence People
Slytherin 101: How to Win Friends and Influence PeopleSlytherin 101: How to Win Friends and Influence People
Slytherin 101: How to Win Friends and Influence People
 
Keeping your culture afloat through a tidal wave
Keeping your culture afloat through a tidal waveKeeping your culture afloat through a tidal wave
Keeping your culture afloat through a tidal wave
 
User Created Content: Maintain accessibility in content you don't control
User Created Content: Maintain accessibility in content you don't controlUser Created Content: Maintain accessibility in content you don't control
User Created Content: Maintain accessibility in content you don't control
 
Kicking impostor syndrome in the head
Kicking impostor syndrome in the headKicking impostor syndrome in the head
Kicking impostor syndrome in the head
 
Care and Feeding of Volunteers
Care and Feeding of VolunteersCare and Feeding of Volunteers
Care and Feeding of Volunteers
 
Sowing the Seeds of Diversity
Sowing the Seeds of DiversitySowing the Seeds of Diversity
Sowing the Seeds of Diversity
 
Be Kind To Your Wrists (you’ll miss them when they’re gone)
Be Kind To Your Wrists (you’ll miss them when they’re gone)Be Kind To Your Wrists (you’ll miss them when they’re gone)
Be Kind To Your Wrists (you’ll miss them when they’re gone)
 
Web Accessibility for the 21st Century
Web Accessibility for the 21st CenturyWeb Accessibility for the 21st Century
Web Accessibility for the 21st Century
 
Servers and Processes: Behavior and Analysis
Servers and Processes: Behavior and AnalysisServers and Processes: Behavior and Analysis
Servers and Processes: Behavior and Analysis
 
Overcoming Impostor Syndrome
Overcoming Impostor SyndromeOvercoming Impostor Syndrome
Overcoming Impostor Syndrome
 
Build Your Own Contributors, One Part At A Time
Build Your Own Contributors, One Part At A TimeBuild Your Own Contributors, One Part At A Time
Build Your Own Contributors, One Part At A Time
 

Recently uploaded

Choose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presenceChoose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presence
rajancomputerfbd
 
Measuring the Impact of Network Latency at Twitter
Measuring the Impact of Network Latency at TwitterMeasuring the Impact of Network Latency at Twitter
Measuring the Impact of Network Latency at Twitter
ScyllaDB
 
Advanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly DetectionAdvanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly Detection
Bert Blevins
 
Best Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdfBest Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdf
Tatiana Al-Chueyr
 
Cookies program to display the information though cookie creation
Cookies program to display the information though cookie creationCookies program to display the information though cookie creation
Cookies program to display the information though cookie creation
shanthidl1
 
Quantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLMQuantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLM
Vijayananda Mohire
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
HackersList
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
SynapseIndia
 
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
Toru Tamaki
 
The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses
Larry Smarr
 
Calgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptxCalgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptx
ishalveerrandhawa1
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
BookNet Canada
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
Emerging Tech
 
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALLBLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
Liveplex
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc
 
The Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive ComputingThe Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive Computing
Larry Smarr
 
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
Kief Morris
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
Adam Dunkels
 
Manual | Product | Research Presentation
Manual | Product | Research PresentationManual | Product | Research Presentation
Manual | Product | Research Presentation
welrejdoall
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
Neo4j
 

Recently uploaded (20)

Choose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presenceChoose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presence
 
Measuring the Impact of Network Latency at Twitter
Measuring the Impact of Network Latency at TwitterMeasuring the Impact of Network Latency at Twitter
Measuring the Impact of Network Latency at Twitter
 
Advanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly DetectionAdvanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly Detection
 
Best Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdfBest Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdf
 
Cookies program to display the information though cookie creation
Cookies program to display the information though cookie creationCookies program to display the information though cookie creation
Cookies program to display the information though cookie creation
 
Quantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLMQuantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLM
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
 
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
 
The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses
 
Calgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptxCalgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptx
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
 
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALLBLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
 
The Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive ComputingThe Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive Computing
 
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
 
Manual | Product | Research Presentation
Manual | Product | Research PresentationManual | Product | Research Presentation
Manual | Product | Research Presentation
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
 

LCA2014 - Introduction to Go

  • 1. Introduction to Go a tutorial for developers Hello! While you’re sitting down, please make sure your Go environment is set up. ! Grab a USB stick that’s floating around and copy the gostick directory somewhere local. ! Then read the included README please!
  • 2. Autobiography • Mark Smith <mark@qq.is> @zorkian • Site Reliability Engineer at Dropbox • Contributes to Dreamwidth Studios • github.com/xb95
  • 3. Today’s Plan • What is Go? Where does it fit? • Obligatory Hello World • Contrived example program • Anti-unicorns • Wrap-up
  • 4. Go in a Nutshell • Designed for building systems • Statically compiled, garbage collected • Static typing (w/some duck typing) • Built-in maps (dicts) and strings
  • 5. Go in a Nutshell • Multi-core support • Concurrency primitives • Closures, etc. etc. • “Somewhere between C and Python”
  • 6. The Go Way • Go is an opinionated language • gofmt, mixedCaps, capitalization for privacy… • Simple is better than complex • The compiler should help with the heavy lifting
  • 8. Hello World package main ! import "fmt" ! func main() { fmt.Println("Hello, LCA 2014!") }
  • 9. Hello World package main ! import "fmt" ! func main() { fmt.Println("Hello, LCA 2014!") }
  • 10. Hello World package main ! import "fmt" ! func main() { fmt.Println("Hello, LCA 2014!") }
  • 11. Hello World package main ! import "fmt" ! func main() { fmt.Println("Hello, LCA 2014!") }
  • 12. Hello World package main ! import "fmt" ! func main() { fmt.Println("Hello, LCA 2014!") }
  • 13. Building Hello World # Do this in your gostick/ copy # You did follow the README? :-) cd helloworld/ go build ./helloworld
  • 14. Getting Real • Go is particularly suited for network services • The standard library is fairly comprehensive • Let’s build an echo server!
  • 15. Echo Server 1. Listen on port for TCP connections 2. Accept connections 3. Read text from connection 4. Write it back to connection
  • 16. Standard Library • Go has a decent standard library • The ecosystem is still fairly young, so it has some holes and some things aren’t well optimized • Well built for network services • http://golang.org/pkg/
  • 17. Tip: Searching When you search the Internet for information, “Go” is a bad keyword; everybody uses “golang”.
  • 18. Echo Server 1. Listen on port for TCP connections 2. Accept connections 3. Read text from connection 4. Write it back to connection
  • 19. Listening for Connections In the “net” package, you’ll find many useful things, including: func Listen(net, laddr string) (Listener, error)
  • 20. Listening for Connections In the “net” package, you’ll find many useful things, including: func Listen(net, laddr string) (Listener, error) package main ! import "net" ! func main() { ! }
  • 21. Listening for Connections In the “net” package, you’ll find many useful things, including: func Listen(net, laddr string) (Listener, error) package main ! import "net" ! func main() { ... := net.Listen("tcp", ":9000") }
  • 22. Variable Definition • Go has two ways of declaring variables, explicit and implicit • Explicit:
 var foobar uint64 • Implicit (type is inferred automatically):
 foobar := thingThatReturnsUint64() • Go strives to save on typing redundant information that the compiler can figure out
  • 23. Error Handling • Using multiple return values to get errors • Idiomatically, you will write this a lot:
 
 results, err := pkg.DoSomething(1, 2)
 if err != nil {
 log.Fatalf(“Failed: %s”, err)
 }
 // carry on and use results • Yes, this gets very verbose… oh well
  • 24. Echo Server 1. Listen on port for TCP connections 2. Accept connections 3. Read text from connection 4. Write it back to connection
  • 25. Connection Pump func Accept() (Conn, error) func main() { listener, err := net.Listen("tcp", ":9000") ! ! ! ! ! ! ! ! ! ! ! }
  • 26. Connection Pump func Accept() (Conn, error) func main() { listener, err := net.Listen("tcp", ":9000") if err != nil { panic(err) } ! ! ! ! ! ! ! ! }
  • 27. Connection Pump func Accept() (Conn, error) func main() { listener, err := net.Listen("tcp", ":9000") if err != nil { panic(err) } ! for { ! ! ! ! } }
  • 28. Connection Pump func Accept() (Conn, error) func main() { listener, err := net.Listen("tcp", ":9000") if err != nil { panic(err) } ! for { client, err := listener.Accept() ! ! ! ! } }
  • 29. Connection Pump func Accept() (Conn, error) func main() { listener, err := net.Listen("tcp", ":9000") if err != nil { panic(err) } ! for { client, err := listener.Accept() if err != nil { continue } ! } }
  • 30. Connection Pump func Accept() (Conn, error) func main() { listener, err := net.Listen("tcp", ":9000") if err != nil { panic(err) } ! for { client, err := listener.Accept() if err != nil { continue } handleClient(client) } }
  • 31. Echo Server 1. Listen on port for TCP connections 2. Accept connections 3. Read text from connection 4. Write it back to connection
  • 32. Client Handler func Read(b []byte) (int, error) func handleClient(client net.Conn) { for { // read from our client // write it back to our client } }
  • 33. Client Handler func Read(b []byte) (int, error) func handleClient(client net.Conn) { for { // read from our client // write it back to our client } } Okay, so what’s a []byte?
  • 34. Primitive Go Types • All of the usual suspects (ints, uints, floats) • Built-in string type (Unicode, immutable) • int and uint are architecture-width • byte is just a synonym for uint8
  • 35. More Types • arrays: of a declared, fixed length • slice: a segment (“slice”) of an array • map: key/value storage • pointer: much like C (uses & and *) • (more to come later)
  • 36. So, []byte… • Let’s make an array of bytes:
 var ary [4096]byte • What if we don’t know the size? Or don’t care? Slices solve this problem:
 var aryslice []byte • This is great, but what is it?
  • 37. Slices Explained var a [16]byte is
  • 38. Slices Explained var a [16]byte is a[3] is
  • 39. Slices Explained var a [16]byte is a[3] is a[6:8] is
  • 40. Slices Explained var a [16]byte is a[3] is a[6:8] is var s []byte is nothing to start with.
  • 41. Slices Explained var a [16]byte is a[3] is a[6:8] is var s []byte is nothing to start with. s = a[6:8]; s is
  • 42. Slices Explained var a [16]byte is a[3] is a[6:8] is var s []byte is nothing to start with. s = a[6:8]; s is s[0] is the same as a[6], etc! A slice is simply a window into a backing array.
  • 43. Slices pt. 2 • Slices are internally a tuple of (array, start, length) • A slice can be moved around (a sliding window) and resized (limited to the backing array size) • Slices are reference types; great for passing to functions
  • 44. Echo Server 1. Listen on port for TCP connections 2. Accept connections 3. Read text from connection 4. Write it back to connection
  • 45. Client Handler func Read(b []byte) (int, error) func handleClient(client net.Conn) { for { ! ! ! ! ! ! } }
  • 46. Client Handler func Read(b []byte) (int, error) func handleClient(client net.Conn) { for { buf := make([]byte, 4096) ! ! ! ! } }
  • 47. Client Handler func Read(b []byte) (int, error) func handleClient(client net.Conn) { for { buf := make([]byte, 4096) numbytes, err := client.Read(buf) ! ! ! ! } }
  • 48. Client Handler func Read(b []byte) (int, error) func handleClient(client net.Conn) { for { buf := make([]byte, 4096) numbytes, err := client.Read(buf) if numbytes == 0 || err != nil { return } ! } }
  • 49. Client Handler func Read(b []byte) (int, error) func handleClient(client net.Conn) { for { buf := make([]byte, 4096) numbytes, err := client.Read(buf) if numbytes == 0 || err != nil { return } client.Write(buf) } }
  • 50. Build & Test # Do this in your gostick/ copy cd part1/ go build ./part1 & telnet localhost 9000 # say something and hit enter
  • 51. More Power • The echo server is great, but can only serve one user at a time! • Concurrent network programming… should we fork for each child? use a threading library? maybe we can implement it using non-blocking I/O… • Stop, stop, stop!
  • 52. Concurrent, Go Style Remember our main accept loop? Let’s tweak it from this… func main() { listener, err := net.Listen("tcp", ":9000") if err != nil { panic(err) } ! for { client, err := listener.Accept() if err != nil { continue } handleClient(client) } }
  • 53. Concurrent, Go Style …to this! func main() { listener, err := net.Listen("tcp", ":9000") if err != nil { panic(err) } ! for { client, err := listener.Accept() if err != nil { continue } go handleClient(client) } }
  • 54. Goroutines • A goroutine is a function executing concurrently with other goroutines • Go multiplexes M goroutines onto N processes, and scales to 100,000+ goroutines (millions possible, use case dependent) • N is by default only 1, you can tune it
  • 55. Goroutines pt. 2 • Everything in Go is designed to be blocking, in essence, and the idea is to use goroutines • This makes reasoning about software much easier • Go also provides deadlock detection and backtraces all living goroutines
  • 56. Echo v2.0, “Chat” • Let’s make a chat server out of our echo server • Design goal: any text from one client is echoed immediately to all connected clients • Well, clearly, our goroutines have to communicate
  • 57. Communication • The common idiom for communicating between threads in most languages is shared memory • This kind of work is notoriously racy, error prone, and hard to implement correctly
  • 58. Communication in Go • “Don’t communicate by sharing memory; share memory by communicating!” • Enter the concept of channels • A built-in goroutine safe method of passing data
  • 59. Basic Channel Use ch := make(chan int) Create a new channel ch <- 5 Write to a channel Read from a channel i := <-ch The channel in this example is an unbuffered channel. Reads block until data is available, writes block until someone reads. Synchronous.
  • 60. Buffered Channels ch := make(chan int, 10) Create a new channel ch <- 5 Write to a channel Read from a channel i := <-ch The difference: buffered channels won’t block when inserting data (unless they’re full).
  • 61. Chat Server • We have to make three main modifications: 1. Store a list of connected clients 2. Get input out of the clients 3. Write each input back to every client • Note: this implementation is a reduced example, so it’s a little unsafe in one place :-)
  • 62. Chat Server • We have to make three main modifications: 1. Store a list of connected clients 2. Get input out of the clients 3. Write each input back to every client • Note: this implementation is a reduced example, so it’s a little unsafe in one place :-)
  • 63. Connected Clients func main() { ... ! ! ! for { client, err := listener.Accept() if err != nil { continue } ! go handleClient(client) } }
  • 64. Connected Clients func main() { ... ! var clients []net.Conn ! for { client, err := listener.Accept() if err != nil { continue } clients = append(clients, client) go handleClient(client) } } Build a slice of clients and then append each new client to the slice. ! The append built-in handles automatically allocating and growing the backing array as necessary.
  • 65. Chat Server • We have to make three main modifications: 1. Store a list of connected clients 2. Get input out of the clients 3. Write each input back to every client • Note: this implementation is a reduced example, so it’s a little unsafe in one place :-)
  • 66. Getting Input func main() { ... ! for { ... clients = append(clients, client) go handleClient(client) } } ! func handleClient(client net.Conn) { for { ... client.Write(buf) } }
  • 67. Getting Input func main() { ... input := make(chan []byte, 10) ! for { ... clients = append(clients, client) go handleClient(client) } } ! func handleClient(client net.Conn) { for { ... client.Write(buf) } }
  • 68. Getting Input func main() { ... input := make(chan []byte, 10) ! for { ... clients = append(clients, client) go handleClient(client, input) } } ! func handleClient(client net.Conn) { for { ... client.Write(buf) } }
  • 69. Getting Input func main() { ... input := make(chan []byte, 10) ! for { ... clients = append(clients, client) go handleClient(client, input) } } ! func handleClient(client net.Conn, input chan []byte) { for { ... client.Write(buf) } }
  • 70. Getting Input func main() { ... input := make(chan []byte, 10) ! for { ... clients = append(clients, client) go handleClient(client, input) } } ! func handleClient(client net.Conn, input chan []byte) { for { ... client.Write(buf) input <- buf } }
  • 71. Getting Input func main() { ... input := make(chan []byte, 10) ! for { ... clients = append(clients, client) go handleClient(client, input) } } ! func handleClient(client net.Conn, input chan []byte) { for { ... client.Write(buf) Removed the Write! input <- buf } }
  • 72. What is Happening? • handleClient still is a blocking read loop, but instead of writing back to the client it writes the bytes onto a channel • main now has a list of all clients and a channel that everybody is writing input to • Final piece: somebody to read from the channel!
  • 73. Chat Server • We have to make three main modifications: 1. Store a list of connected clients 2. Get input out of the clients 3. Write each input back to every client • Note: this implementation is a reduced example, so it’s a little unsafe in one place :-)
  • 74. The Chat Manager func main() { ... var clients []net.Conn input := make(chan []byte, 10) ! ! ! ! We’ve ! ! ! ! ... } seen this all before…
  • 75. The Chat Manager func main() { ... var clients []net.Conn input := make(chan []byte, 10) go func() { ! ! ! ! ! }() ... } You can create goroutines out of closures, too. !
  • 76. The Chat Manager ! func main() { ... var clients []net.Conn input := make(chan []byte, 10) go func() { for { message := <-input ! ! } }() ... } ! ! This is all blocking!
  • 77. The Chat Manager ! func main() { ... var clients []net.Conn This input := make(chan []byte, 10) go func() { for { message := <-input for _, client := range clients { ! } } }() ... } ! ! is all blocking!
  • 78. range and _ for _, client := range clients {..} • The range keyword iterates over maps/slices/ arrays and returns the key (or index) and value • Underscore (_) is the anonymous variable (“blank identifier”), you can use it to discard results
  • 79. The Chat Manager func main() { ... var clients []net.Conn input := make(chan []byte, 10) go func() { for { message := <-input for _, client := range clients { client.Write(message) } } }() ... }
  • 80. Build & Test # Do this in your gostick/ copy cd part2/ go build ./part2 & telnet localhost 9000 # say something and hit enter, now connect # again in another window and chat! :-)
  • 81. Echo 3.0, “Frotzer” • We’re entering the land of extremely contrived tutorial examples, but… • Let’s give our chat server some behaviors! • When a user chats, we apply some formatting rules before sending it out to other users
  • 82. But First: More Type Talk! • Go doesn’t have classes (or objects, really) • However, you have named types, and methods are attached to named types:
 
 
 
 type Uppercaser struct{} ! func (self Uppercaser) Frotz(input []byte) []byte { return bytes.ToUpper(input) }
  • 83. Um, struct{}? • Go supports structs, very much like any other language that has structs • The empty struct is often used for hanging methods • Instantiating a struct type:
 foobar := Lowercaser{}
 foobar.Frotz(“HELLO”) // “hello”
  • 84. Interfaces • In Go, an interface specifies a collection of methods attached to a name • Interfaces are implicit (duck typed)
 
 
 
 type Frotzer interface { Frotz([]byte) []byte } ! type Uppercaser struct{} func (self Uppercaser) Frotz(input []byte) []byte { return bytes.ToUpper(input) }
  • 85. Implementing Frotzing func chatManager(clients *[]net.Conn, input chan []byte ) { for { message := <-input for _, client := range *clients { client.Write(message) } } } This is the input handler loop we built a few minutes ago, except now we pulled it out of main and made it a function.
  • 86. Implementing Frotzing func chatManager(clients *[]net.Conn, input chan []byte, frotz Frotzer) { for { message := <-input for _, client := range *clients { client.Write(frotz.Frotz(message)) } } } Now it takes a third argument: an interface. Any type that implements Frotzer can be used!
  • 87. Making Frotzers These are both named types, and both implement (implicitly!) the Frotzer interface. Thanks, compiler! type Uppercaser struct{} func (self Uppercaser) Frotz(input []byte) []byte { return bytes.ToUpper(input) } ! type Lowercaser struct{} func (self Lowercaser) Frotz(input []byte) []byte { return bytes.ToLower(input) }
  • 88. A New Main func main() { ... var clients []net.Conn input := make(chan []byte, 10) go chatManager(&clients, input) ! ! for { client, err := listener.Accept() if err != nil { continue } clients = append(clients, client) go handleClient(client, input) } }
  • 89. A New Main func main() { ... var clients []net.Conn input := make(chan []byte, 10) go chatManager(&clients, input, Lowercaser{}) go chatManager(&clients, input, Uppercaser{}) ! for { client, err := listener.Accept() if err != nil { continue } clients = append(clients, client) go handleClient(client, input) } }
  • 90. A New Main pt. 2 • The chatManager functions are spawned into separate goroutines • Channels are goroutine safe, so they end up interleaving reads (not guaranteed!) • chatManager doesn’t know what you’re passing it as a Frotzer, it just knows it can call Frotz on it
  • 91. Build & Test # Do this in your gostick/ copy cd part3/ go build ./part3 & telnet localhost 9000 # say something and hit enter, your text # should alternate UPPER/lower
  • 92. Review • A multi-user chat server demonstrating many core parts of the Go programming language • Built-in concurrency that is easy to use and trivially allows relatively powerful constructions • A classless, statically type system that still enables many OO concepts
  • 93. Go is Awesome :-) This slide should have unicorns and bunnies on it
  • 94. Things That Aren’t Unicorns Yet • The GC is generally pretty solid, but if you are doing many allocations and need performance, you have to do the usual tricks • Standard library is pretty young and not optimized • Overall ecosystem is small (but growing, hi!)
  • 95. Also: The Scheduler • It’s new and has room for improvement • Heavy use of channels between goroutines is probably faster in one process • You’ll have to play with GOMAXPROCS and understand your application
  • 96. Topics Undiscussed • Building your own packages (it’s easy) • Importing from external repositories
 import pcap “github.com/akrennmair/gopcap” • Using gofmt (do it!) • switch, select, etc. • Type assertions, reflection, even more etc.
  • 97. Thank you! Mark Smith <mark@qq.is> @zorkian
 SRE at Dropbox (we’re hiring!) • Some recommended reading:
 Effective Go golang.org/doc/effective_go.html
 FAQ golang.org/doc/faq • Many more talks and presentations:
 code.google.com/p/go-wiki/wiki/GoTalks • The Go Playground! play.golang.org