From: Sebastian Harl Date: Sat, 4 Jun 2016 13:04:16 +0000 (+0200) Subject: Add the presentation slides for the intro and gRPC talks. X-Git-Url: https://git.tokkee.org/?a=commitdiff_plain;h=refs%2Fheads%2Fmaster;p=go-talk.git Add the presentation slides for the intro and gRPC talks. The slides are in German. --- diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..722aed4 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "tex/tokkeebeamer"] + path = tex/tokkeebeamer + url = git://git.tokkee.org/tokkeebeamer.git diff --git a/README b/README index 351ecbc..9cdba6e 100644 --- a/README +++ b/README @@ -1,7 +1,7 @@ - tokkee's Go and gRPC talk - =========================== + tokkee's Go and gRPC talks + ============================ - Supporting material for a talk about Go and gRPC. + Supporting material for tokkee's talks about Go and gRPC. Setup ----- @@ -46,9 +46,23 @@ Rebuilding the generated proto / gRPC code $ protoc src/tokkee.org/go-talk/grpc/proto/backend/backend.proto \ --go_out=plugins=grpc:. +Presentation slides +------------------- + + The 'tex' subdirectory includes the LaTeX code for the presentation slides. + + Generate PDF documents: + + $ cd $GOPATH/src/tokkee.org/go-talk + $ git submodule update --init + $ cd tex; make + Author ------ Sebastian 'tokkee' Harl Licensed under the 2-clause BSD license. See LICENSE for details. + + For license conditions of subpackages, see the respective LICENSE files in + the subdirectories. diff --git a/tex/.gitignore b/tex/.gitignore new file mode 100644 index 0000000..40f229b --- /dev/null +++ b/tex/.gitignore @@ -0,0 +1,9 @@ +*.aux +*.log +*.nav +*.out +*.snm +*.toc +*.vrb +go-intro.pdf +go-grpc.pdf diff --git a/tex/LICENSE b/tex/LICENSE new file mode 100644 index 0000000..9088956 --- /dev/null +++ b/tex/LICENSE @@ -0,0 +1,108 @@ +Copyright (c) 2013-2016 Sebastian 'tokkee' Harl +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +----------------------------------------------------------------------------- + +The Go gopher (gopher.png) was designed by Renee French. +(http://reneefrench.blogspot.com/) + +The design is licensed under the Creative Commons 3.0 Attributions license. +Read this article for more details: https://blog.golang.org/gopher + +You are free: +* to share – to copy, distribute and transmit the work +* to remix – to adapt the work + +Under the following conditions: +* attribution – You must attribute the work in the manner specified by the + author or licensor (but not in any way that suggests that they endorse you + or your use of the work). +* share alike – If you alter, transform, or build upon this work, you may + distribute the resulting work only under the same or similar license to this + one. + +Source: http://golang.org/doc/gopher/ + +----------------------------------------------------------------------------- + +The gRPC logo (grpc.pdf) is licensed under the 3-clause BSD license: + +Copyright (c) 2015, grpc +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of grpc.github.io nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Source: https://github.com/grpc/grpc.github.io + +----------------------------------------------------------------------------- + +The LaTeX lstlistings language definition for Go (lstlang0.sty) is licensed +under the MIT license: + +The MIT License (MIT) + +Copyright (c) 2016 Uriel Corfa + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +Source: https://github.com/korfuri/golang-latex-listings/ diff --git a/tex/Makefile b/tex/Makefile new file mode 100644 index 0000000..fb8859c --- /dev/null +++ b/tex/Makefile @@ -0,0 +1,13 @@ +TOKKEEBEAMER = tokkeebeamer +include $(TOKKEEBEAMER)/tokkeebeamer.mk + +all: go-intro.pdf go-grpc.pdf + +go-intro.pdf: go-intro.tex tokkeebeamer/*.sty Makefile +go-grpc.pdf: go-grpc.tex tokkeebeamer/*.sty Makefile + +clean: + rm -f *.aux *.log *.nav *.out *.snm *.toc *.vrb + rm -f go-intro.pdf go-grpc.pdf + +.PHONY: all clean diff --git a/tex/go-grpc.tex b/tex/go-grpc.tex new file mode 100644 index 0000000..f97072a --- /dev/null +++ b/tex/go-grpc.tex @@ -0,0 +1,426 @@ +% +% Copyright (C) 2015-2016 Sebastian 'tokkee' Harl +% All rights reserved. +% +% Redistribution and use in source and binary forms, with or without +% modification, are permitted provided that the following conditions +% are met: +% 1. Redistributions of source code must retain the above copyright +% notice, this list of conditions and the following disclaimer. +% 2. Redistributions in binary form must reproduce the above copyright +% notice, this list of conditions and the following disclaimer in the +% documentation and/or other materials provided with the distribution. +% +% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +% ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +% TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +% PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR +% CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +% EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +% PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +% OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +% WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +% OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +% +\documentclass[presentation]{beamer} +\uselanguage{German} + +\usetheme{tokkee} +\usefonttheme{professionalfonts} + +\setbeamercolor*{block body}{fg=black,bg=white} +\setbeamercolor*{block title}{use=titlelike,fg=titlelike.fg!80!black,bg=black!10} + +\usepackage{fontspec,xunicode,polyglossia} +\setdefaultlanguage[spelling=new]{german} + +\usepackage{graphicx} +\usepackage{xcolor} +\definecolor{darkgreen}{rgb}{0,0.39,0} + +\usepackage{listings} +\lstset{ + basicstyle=\scriptsize, + language=Go, + frame=single, + numbers=left, + keywordstyle=\bfseries\color{darkgreen}, + commentstyle=\itshape\color{blue}, + stringstyle=\color{red}, + showstringspaces=false, + backgroundcolor=\color{lightgray!25}, + literate=% + {Ö}{{\"O}}1 + {Ä}{{\"A}}1 + {Ü}{{\"U}}1 + {ß}{{\ss}}1 + {ü}{{\"u}}1 + {ä}{{\"a}}1 + {ö}{{\"o}}1, +} + +\usepackage[overlay,absolute]{textpos} + +\usepackage{tikz} +\usetikzlibrary{shadows} +\usetikzlibrary{shapes} + +\newcommand{\collectd}{\textsf{\textbf{collect}d}} + +\title{Web-Services mit Go} +\subtitle{Go-Features an Hand von Beispielen} + +\titlegraphic{} + +\copyrightinfo{\copyright{} 2015-2016 Sebastian `tokkee' Harl} + +\author[Sebastian Harl]{Sebastian `tokkee' Harl\\ + $<$sh@tokkee.org$>$} + +\date[2015-2016]{} + +\AtBeginSection[] +{ + \begin{frame} + \begin{center} + \Large + \titlebox{\secname} + \end{center} + \end{frame} +} + +\begin{document} + +\begin{frame}[plain] + \titlepage +\end{frame} + +\begin{frame}{Überblick} + \textbf{Was ist Go?} + + \textit{Go is an open source programming language that makes it easy to + build simple, reliable, and efficient software.}\\[10mm] + + \url{https://golang.org} + + \begin{tikzpicture}[remember picture,overlay] + \node[anchor=north east] at (current page.east) + {\includegraphics[width=.7\textwidth]{gopher}}; + \end{tikzpicture} +\end{frame} + +\begin{frame}{Web-Services} + \begin{itemize} + \item HTTP Frontend + \begin{itemize} + \item Viele parallele Client-Anfragen + \item Eine oder mehrere Verbindungen zu Backends + \end{itemize} + \item Backend ("`Business Logic"') + \begin{itemize} + \item Viele parallele Anfragen vom Frontend + \item Eine oder mehrere Datenbank-Verbindungen oder Interaktion mit + anderen Backends + \end{itemize} + \item Datenbank\\[3mm] + + \item[$\Rightarrow$] skalierbare Micro-Services~/ \textbf{lose + Kopplung}\\[5mm] + \end{itemize} + + \textbf{Auch:} Gleiche Prinzipien bei Integration mit anderen Lösungen +\end{frame} + +\begin{frame}{Einschub: Go Standard Bibliothek} + \url{https://golang.org/pkg/}\\[5mm] + + \begin{itemize} + \item Crypto + \item Datenbanken + \item Go Parser + \item Netzwerk, HTTP, SMTP, etc. + \item Datenstrukturen\\[7mm] + \end{itemize} + + \textbf{Mehr?} $\Rightarrow$ \url{https://godoc.org/} +\end{frame} + +\begin{frame}[fragile]{Ein Webserver} + \begin{lstlisting} +import (...) + +func main() { + http.HandleFunc("/hallo", sageHallo) + log.Fatal(http.ListenAndServe(":9999", nil)) +} + +func sageHallo(w http.ResponseWriter, r *http.Request) { + fmt.Fprintf(w, "Hallo %s", r.RemoteAddr) +} +\end{lstlisting} + + \begin{itemize} + \item \url{https://golang.org/pkg/log/} + \item \url{https://golang.org/pkg/net/http/} + \end{itemize} +\end{frame} + +\begin{frame}[fragile]{Ein Webserver -- Templates} + \begin{lstlisting} +var tmpl = template.Must( + template.New("results").Parse(` + +{{.Title}} + + + +

Hallo {{.Name}}

+ +`)) + \end{lstlisting} + + \begin{itemize} + \item \url{https://golang.org/pkg/html/template/} + \end{itemize} +\end{frame} + +\begin{frame}[fragile]{Ein Webserver -- Templates (2)} + \begin{lstlisting} +func sageHallo(...) { + d := struct { + Title, Name string + }{"Hallo Welt", r.RemoteAddr} + + var buf bytes.Buffer + if err := tmpl.Execute(&buf, d); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + io.Copy(w, &buf) +} + \end{lstlisting} + + \begin{itemize} + \item \url{https://golang.org/pkg/bytes/} + \item \url{https://golang.org/pkg/io/} + \end{itemize} +\end{frame} + +\begin{frame}[fragile]{Einschub: io.Writer} + \begin{itemize} + \item Warum funktioniert fmt.Printf, tmpl.Execute, http.Error, io.Copy + eigentlich mit dem http.ResponseWriter und bytes.Buffer? + \end{itemize} + + \begin{lstlisting} +package io +type Writer interface { + Write(p []byte) (n int, err error) +} + \end{lstlisting} + + \begin{itemize} + \item[$\Rightarrow$] \textbf{Sehr} einfaches Interface + \item[$\Rightarrow$] \texttt{http.ResponseWriter} und + \texttt{bytes.Buffer} implementieren es\\[7mm] + \end{itemize} + + Viele andere Beispiele ... +\end{frame} + +\begin{frame}[fragile]{Viele Backend-Abfragen} + \begin{lstlisting} +func Query(*Request) (*Response, error) { ... } + +func anfrage(w http.ResponseWriter, r *http.Request) { + requests := []*Request{...} + + responses := make([]*Reponse, len(requests)) + errCh := make(chan error, len(requests)) + + for i, req := range requests { + go func(i int, req *Request) { + var err error + responses[i], err = Query(req) + errCh <- err + }(i, req) + } + + // ... + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{Viele Backend-Abfragen (2)} + \begin{lstlisting} + ... + timeout := time.After(50*time.Millisecond) + + for range requests { + select { + case err := <-errCh: + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + case <-timeout: + http.Error(w, "timeout", http.StatusRequestTimeout) + return + } + } + // Alle Ergebnisse verfügbar. + \end{lstlisting} + + \begin{itemize} + \item Siehe auch \url{https://golang.org/pkg/sync/#WaitGroup} + \end{itemize} +\end{frame} + +\begin{frame}[fragile]{Spezielle Fehlerbehandlung} + \begin{lstlisting} + go func(req *Request) { + var err error + defer func() { + if e := recover(); e != nil { + err = fmt.Errorf("error while querying backend: %v", e) + } + errCh <- err + }() + + responses[i], err = Query(req) + }(req) + \end{lstlisting} +\end{frame} + +\begin{frame}{Backends -- gRPC} + \textbf{Beispiel: Backend Kommunikation~/ API}\\[5mm] + + \textit{A high performance, open source, general RPC framework that puts + mobile and HTTP/2 first.}\\[10mm] + + \url{https://grpc.io}\\ + \hfill\includegraphics[width=.3\textwidth]{grpc} +\end{frame} + +\begin{frame}{gRPC Überblick} + \url{https://github.com/google/protobuf}\\[5mm] + + \begin{itemize} + \item gRPC basiert auf Protocol Buffers + \item Unterstützung diverser Sprachen\newline + C++, Java, Go, Python, \ldots + \end{itemize} +\end{frame} + +\begin{frame}[fragile]{gRPC Beispiel} + \begin{lstlisting}[morekeywords={syntax,service,message}] +syntax "proto3"; + +package mein_service; + +service Backend { + rpc Query(QueryRequest) return (QueryResponse); + + // ... +} + +message QueryRequest { + string query = 1; +} + +message QueryResponse { + string type = 1; + int64 n = 2; +} + \end{lstlisting} +\end{frame} + +\begin{frame}{gRPC mit Go} + \begin{itemize} + \item Die "`protobuf"' Datei muss mittels des Protobuf Compilers und einer + gRPC Compiler-Erweiterung übersetzt werden + \item Der Compiler erzeugt Go Code, welcher Interfaces und generischen + Code erzeugt + \item Das Interface entspricht im Wesentlichen der \texttt{service} + Definition + \item Das Interface muss für den Server implementiert werden + \item Generischer Client-Code sollte ausreichen\newline + $\rightarrow$ API Entwurf!\\[7mm] + \end{itemize} + + \url{https://github.com/grpc/grpc-go}\\ + \url{https://golang.org/x/net/context} +\end{frame} + +\begin{frame}[fragile]{gRPC mit Go: Server} + \begin{lstlisting} +import pb "tokkee.net/mein_service/service_proto" + +type server struct{} + +func (*server) Query(ctx context.Context, + in *pb.QueryRequest) (*pb.QueryResponse, error) { + + n, err := runQuery(in.Query) + if err != nil { + return nil, err + } + return &pb.QueryResponse{ + Type: "irgendwas", + N: n, + }, nil +} + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{gRPC mit Go: Server (2)} + \begin{lstlisting} +func main() { + l, err := net.Listen("tcp", port) + if err != nil { + log.Fatal(err) + } + + s := grpc.NewServer() + pb.RegisterBackendServer(s, &server{}) + s.Serve(l) +} + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{gRPC mit Go: Client} + \begin{lstlisting} +func main() { + ctx := context.Background() + + conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure()) + if err != nil { + log.Fatal(err) + } + defer conn.Close() + c := pb.NewBackendClient(conn) + + res, err := c.Query(ctx, &pb.QueryRequest{ + Query: "ein query", + }) + if err != nil { + log.Fatal(err) + } + fmt.Printf("Antwort vom Typ %q: %d\n", res.Type, res.N) +} + \end{lstlisting} +\end{frame} + +\begin{frame}{\inserttitle} + \begin{center} + Danke für die Aufmerksamkeit\\[2mm] + {\Large Fragen, Kommentare?}\\[6mm] + + \url{https://golang.org}\quad—\quad + \url{https://github.com/grpc/grpc-go} + \end{center} +\end{frame} + +\end{document} + +% vim: set shiftwidth=2 softtabstop=2 tabstop=8 noexpandtab spelllang=de_de : diff --git a/tex/go-intro.tex b/tex/go-intro.tex new file mode 100644 index 0000000..cb532e4 --- /dev/null +++ b/tex/go-intro.tex @@ -0,0 +1,493 @@ +% +% Copyright (C) 2015-2016 Sebastian 'tokkee' Harl +% All rights reserved. +% +% Redistribution and use in source and binary forms, with or without +% modification, are permitted provided that the following conditions +% are met: +% 1. Redistributions of source code must retain the above copyright +% notice, this list of conditions and the following disclaimer. +% 2. Redistributions in binary form must reproduce the above copyright +% notice, this list of conditions and the following disclaimer in the +% documentation and/or other materials provided with the distribution. +% +% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +% ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +% TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +% PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR +% CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +% EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +% PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +% OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +% WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +% OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +% +\documentclass[presentation]{beamer} +\uselanguage{German} + +\usetheme{tokkee} +\usefonttheme{professionalfonts} + +\usepackage{xeCJK} +\renewcommand\CJKfamilydefault{\CJKsfdefault} +\setCJKsansfont{WenQuanYi Zen Hei} + +\setbeamercolor*{block body}{fg=black,bg=white} +\setbeamercolor*{block title}{use=titlelike,fg=titlelike.fg!80!black,bg=black!10} + +\usepackage{fontspec,xunicode,polyglossia} +\setdefaultlanguage[spelling=new]{german} + +\usepackage{graphicx} +\usepackage{xcolor} +\definecolor{darkgreen}{rgb}{0,0.39,0} + +\usepackage{listings} +\lstset{ + language=Go, + frame=single, + numbers=left, + keywordstyle=\bfseries\color{darkgreen}, + commentstyle=\itshape\color{blue}, + stringstyle=\color{red}, + showstringspaces=false, + backgroundcolor=\color{lightgray!25}, + literate=% + {Ö}{{\"O}}1 + {Ä}{{\"A}}1 + {Ü}{{\"U}}1 + {ß}{{\ss}}1 + {ü}{{\"u}}1 + {ä}{{\"a}}1 + {ö}{{\"o}}1, +} + +\usepackage[overlay,absolute]{textpos} + +\usepackage{tikz} +\usetikzlibrary{shadows} +\usetikzlibrary{shapes} + +\title[Programmieren mit Go]{Programmieren mit Go} + +\titlegraphic{} + +\copyrightinfo{\copyright{} 2015-2016 Sebastian `tokkee' Harl} + +\author[Sebastian Harl]{Sebastian `tokkee' Harl\\ + $<$sh@tokkee.org$>$} + +\date[2015-2016]{} + +\AtBeginSection[] +{ + \begin{frame} + \begin{center} + \Large + \titlebox{\secname} + \end{center} + \end{frame} +} + +\begin{document} + +\begin{frame}[plain] + \titlepage +\end{frame} + +\begin{frame}{Überblick} + \textbf{Was ist Go?} + + \begin{itemize} + \item \url{https://golang.org/} + \item Open Source Programmiersprache + \item imperativ, Interfaces, Pakete + \item statisch typisiert, kompiliert + \item Nebenläufigkeit + \item Garbage Collection + \end{itemize} + + \begin{tikzpicture}[remember picture,overlay] + \node[anchor=east] at (current page.east) + {\includegraphics[width=.7\textwidth]{gopher}}; + \end{tikzpicture} +\end{frame} + +\begin{frame}[fragile]{Hallo 世界} + \begin{lstlisting} +package main + +import "fmt" + +func main() { + fmt.Println("Hallo 世界") +} + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{Programm übersetzen / ausführen} + \begin{lstlisting}[language=bash,numbers=none] +% go build -o hallo hallo.go +% ./hallo +Hallo 世界 + +% go run hallo.go +Hallo 世界 + \end{lstlisting} +\end{frame} + +\begin{frame}{Go Playground} + \begin{center} + \fbox{\includegraphics[width=.9\textwidth]{playground}} + \end{center} +\end{frame} + +\begin{frame}[fragile]{Pakete / Bibliotheken} + \begin{lstlisting} +package zeichenkette + +func Rückwärts(s string) string { + r := []rune(s) + for i := 0; i < len(r)/2; i++ { + j := len(r) - i - 1 + r[j], r[i] = r[i], r[j] + } + return string(r) +} + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{Pakete verwenden} + \begin{itemize} + \item \texttt{\$GOPATH/src} ist der Suchpfad für extra Pakete + \item \texttt{import "$<$paketname$>$"} + \end{itemize} + + \begin{lstlisting} +package main + +import ( + "fmt" + + zk "tokkee.org/zeichenkette" +) + +func main() { + fmt.Println(zk.Rückwärts("Hallo 世界")) +} + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{Arbeitsumgebung} + \begin{verbatim} +$GOPATH + |\ + | `- bin/ + | \ + | `- hallo + \ + `- src/ + \ + `- hallo/ + \ + `- hallo.go + \end{verbatim} +\end{frame} + +\begin{frame}{Arbeitsumgebung (2)} + \begin{itemize} + \item \lstinline[language=sh]{go build -o hallo_welt hallo} + \item \lstinline[language=sh]{go install hallo} + \item \lstinline[language=sh]{go doc hallo} + \end{itemize} +\end{frame} + +\begin{frame}[fragile]{Fehlerbehandlung} + \begin{lstlisting} +func machEs() (*Object, error) { + var o Object + if err := o.init(); err != nil { + return nil, err + } + return &o, nil +} + +func main() { + o, err := machEs() + if err != nil { + log.Exitf("Fehler: %v\n", err) + } + // ... + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{Komplexe Datenstrukturen} + \textbf{Array / Slice} + \begin{lstlisting} +var array [3]string +array[0] = "ein" +array[1] = "String" +fmt.Println(array) + \end{lstlisting} + + \begin{lstlisting} +var slice []string +slice = array[:] +slice = append(slice, "usw", "usf") +slice = []string{"ein", "anderer", "String"} +fmt.Println(slice) + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{Komplexe Datenstrukturen (2)} + \textbf{Map} + \begin{lstlisting} +var m map[string]int +m = make(map[string]int) // Map anlegen +m = map[string]int{ // Map initialisieren + "a": 1, + "b": 2, +} +m["c"] = 3 +fmt.Println(m["a"]) + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{Komplexe Datenstrukturen (3)} + \textbf{Struct} + \begin{lstlisting} +type Ding struct { + privat float32 + Öffentlich string +} +d := Ding{ + Öffentlich: "Daten für Alle!", + privat: 47.11, +} +d.privat = 3.1415926535 +fmt.Println(d) + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{Komplexe Datenstrukturen (4)} + \textbf{Interface / Methoden} + \begin{lstlisting} +type Macher interface { + Mach(int, int) string +} +type MeinMacher struct {} +func (m MeinMacher) Mach(a, b int) string { + return fmt.Sprintf("%d x %d = %d", a, b, a*b) +} + \end{lstlisting} +\end{frame} + +\begin{frame}{Übung: Quadratwurzel} + \url{https://go-tour-de.appspot.com/flowcontrol/8}\\ + \url{https://de.wikipedia.org/wiki/Newton-Verfahren}\\[5mm] + + Berechne die Quadratwurzel (\lstinline{Wurzel(x float64)}) mit Hilfe des + Newton-Verfahren: + + \begin{equation*} + z_{n+1} = z_n - \frac{z_n^2 - x}{2 * z_n} + \end{equation*} + + Erstelle dazu ein eigenes Paket und ein Programm zum testen. Verwende + entweder eine Schleife mit fester Anzahl an Durchläufen oder bis sich das + Ergebnis nicht (kaum) mehr ändert. +\end{frame} + +\begin{frame}{Die Standard-Bibliothek} + \url{https://golang.org/pkg/}\\[5mm] + + \begin{itemize} + \item Crypto + \item Datenbanken + \item Go Parser + \item Netzwerk, HTTP, SMTP, etc. + \item Datenstrukturen + \end{itemize} +\end{frame} + +\begin{frame}{Weitere Bibliotheken} + \url{https://godoc.org/}\\[5mm] + + \begin{itemize} + \item Vielzahl an Open Source Bibliotheken + \item \lstinline[language=sh]{go get github.com/user/pkg} + \item \url{https://gopkg.in} + \begin{itemize} + \item Versionierung von Bibliotheken auf Github + \item \url{v3} zeigt auf Branch/Tag \url{v3}, \url{v3.N} oder + \url{v3.N.M} + \item \url{gopkg.in/pkg.v3} $\rightarrow$ \url{github.com/go-pkg/pkg} + \item \url{gopkg.in/user/pkg.v3} $\rightarrow$ + \url{github.com/user/pkg} + \end{itemize} + \end{itemize} +\end{frame} + +\begin{frame}[fragile]{Ein Webserver} + \url{https://golang.org/pkg/net/http/} + \begin{lstlisting} +func main() { + http.HandleFunc("/hallo", sageHallo) + log.Fatal(http.ListenAndServe(":9999", nil)) +} + +func sageHallo(w http.ResponseWriter, + r *http.Request) { + + fmt.Fprintf(w, "Hallo %s", r.RemoteAddr) +} + \end{lstlisting} +\end{frame} + +\begin{frame}{Nebenläufigkeit} + \textbf{Alle Anfragen werden nebenläufig behandelt.}\\[5mm] + + \begin{itemize} + \item Goroutinen + \begin{itemize} + \item \texttt{go f(args)} + \item leichtgewichtige Threads + \item hunderte oder tausende werden effizient verwaltet + \end{itemize} + \item Channels + \begin{itemize} + \item Kommunikation zwischen Goroutinen + \end{itemize} + \item \texttt{select} + \begin{itemize} + \item warten auf I/O und Channels + \end{itemize} + \end{itemize} +\end{frame} + +\begin{frame}[fragile]{Goroutinen} + \begin{lstlisting} +errCh := make(chan error, 2) + +go func() { + errCh <- machEs() +}() +go func() { + errCh <- undDas() +}() + +go machEtwasImHintergrund() + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{Goroutinen (2)} + \url{https://golang.org/pkg/time/} + \begin{lstlisting} +timeout := time.After(50*time.Millisecond) +for i := 0; i < cap(errCh); i++ { + select { + case err := <- errCh: + if err != nil { + return err + } + case <-timeout: + return fmt.Errorf("timeout(%d)", i) + } +} + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{Goroutinen (3)} + \textbf{Synchronisierung}\\ + \url{https://golang.org/pkg/sync/} + \begin{lstlisting} +daten := []Object{...} +var wg sync.WaitGroup +for _, d := range daten { + wg.Add(1) + go func(o Object) { + defer wg.Done() + verarbeite(o) + }(d) // <- !!! +} +wg.Wait() + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{Unit Tests} + \url{https://golang.org/pkg/testing/} + \begin{lstlisting} +package zeugs + +// mult multipliziert die beiden +// übergebenen Argumente und gibt +// das Ergebnis zurück. +func mult(a, b int) int { + return a * b +} + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile]{Unit Tests (2)} + \begin{lstlisting} +package zeugs +func TestMult(t *testing.T) { + for _, test := range []struct{ + a, b, want int + }{ + {3, 4, 12}, + {7, 8, 56}, + } { + if r := mult(test.a, test.b); r != test.want { + t.Errorf("mult(%d, %d) = %d; want %d", + test.a, test.b, r, test.want) + } + } +} + \end{lstlisting} +\end{frame} + +\begin{frame}{Übung: Äquivalente Binärbäume} + \url{https://go-tour-de.appspot.com/concurrency/7}\\ + \url{https://godoc.org/golang.org/x/tour/tree}\\ + \url{https://de.wikipedia.org/wiki/Binärbaum}\\[5mm] + + \begin{itemize} + \item Implementiere die \lstinline{Same(t1, t2 *tree.Tree)} Funktion aus + der Online-Übung. + \item Zusätzlich: Erstelle einen Unit-Test für die Funktion. + \end{itemize} +\end{frame} + +\begin{frame}[fragile]{Werkzeuge} + \textbf{Go ist dazu gedacht, in Werkzeugen verwendet zu werden + (\texttt{go/ast}, etc.)}\\[5mm] + + \begin{itemize} + \item gofmt, goimports + \item godoc, \url{https://godoc.org/} + \item IDE und Editor Unterstützung + \end{itemize} + + \textbf{vim:} + \begin{lstlisting}[language=bash,morekeywords={autocmd,let}] +autocmd filetype go + \ autocmd BufWritePre Fmt +let g:gofmt_command = "goimports" + \end{lstlisting} +\end{frame} + +\begin{frame}{\inserttitle} + \begin{center} + Danke für die Aufmerksamkeit\\[2mm] + {\Large Fragen, Kommentare?}\\[6mm] + + \url{https://tour.golang.org}\quad—\quad + \url{https://play.golang.org} + \end{center} +\end{frame} + +\end{document} + +% vim: set shiftwidth=2 softtabstop=2 tabstop=8 noexpandtab spelllang=de_de : diff --git a/tex/gopher.png b/tex/gopher.png new file mode 100644 index 0000000..5d701c0 Binary files /dev/null and b/tex/gopher.png differ diff --git a/tex/grpc.pdf b/tex/grpc.pdf new file mode 100644 index 0000000..3ff0476 Binary files /dev/null and b/tex/grpc.pdf differ diff --git a/tex/lstlang0.sty b/tex/lstlang0.sty new file mode 100644 index 0000000..399a024 --- /dev/null +++ b/tex/lstlang0.sty @@ -0,0 +1,35 @@ +%% Listings definition for Go language +%% Go language reference : http://www.golang.org +%% Author : Uriel Corfa +%% Project home: https://bitbucket.org/korfuri/golang-latex-listings + +\ProvidesFile{lstlang0.sty} + [2012/04/13 1.1 listings language file for GoLang] +\lst@definelanguage{Go}{ + % Keywords as defined in the BNF + morekeywords=[1]{break,default,func,interface,% + case,defer,go,map,struct,chan,else,goto,package,% + switch,const,fallthrough,if,range,type,continue,% + for,import,return,var,select}, + % Special identifiers, builtin functions + morekeywords=[2]{make,new,nil,len,cap,copy,complex,% + real,imag,panic,recover,print,println,iota,close,% + closed,_,true,false,append,delete}, + % Basic types + morekeywords=[3]{% + string,int,uint,uintptr,double,float,byte,% + int8,int16,int32,int64,int128,% + uint8,uint16,uint32,uint64,uint128,% + float32,float64,complex64,complex128,% + rune}, + % Strings : "toto", 'toto', `toto` + morestring=[b]{"}, + morestring=[b]{'}, + morestring=[b]{`}, + % Comments : /* comment */ and // comment + comment=[l]{//}, + morecomment=[s]{/*}{*/}, + % Options + sensitive=true +} +\endinput diff --git a/tex/playground.png b/tex/playground.png new file mode 100644 index 0000000..354934d Binary files /dev/null and b/tex/playground.png differ diff --git a/tex/tokkeebeamer b/tex/tokkeebeamer new file mode 160000 index 0000000..dfe1e78 --- /dev/null +++ b/tex/tokkeebeamer @@ -0,0 +1 @@ +Subproject commit dfe1e789923b1c5e33cca4e06a123fbf6bf4036f