Update first lecture
This commit is contained in:
parent
4006009c2c
commit
1f1c1870c6
9 changed files with 334 additions and 0 deletions
BIN
lectures/00-intro/book.jpg
Normal file
BIN
lectures/00-intro/book.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 81 KiB |
29
lectures/00-intro/counter.go
Normal file
29
lectures/00-intro/counter.go
Normal file
|
@ -0,0 +1,29 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
counter int
|
||||
mu sync.Mutex
|
||||
)
|
||||
|
||||
func main() {
|
||||
http.HandleFunc("/", handler)
|
||||
log.Fatal(http.ListenAndServe("localhost:8000", nil))
|
||||
}
|
||||
|
||||
func handler(w http.ResponseWriter, r *http.Request) {
|
||||
var i int
|
||||
|
||||
mu.Lock()
|
||||
i = counter
|
||||
counter++
|
||||
mu.Unlock()
|
||||
|
||||
fmt.Fprintf(w, "counter = %d\n", i)
|
||||
}
|
22
lectures/00-intro/dup.go
Normal file
22
lectures/00-intro/dup.go
Normal file
|
@ -0,0 +1,22 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
counts := make(map[string]int)
|
||||
input := bufio.NewScanner(os.Stdin)
|
||||
for input.Scan() {
|
||||
counts[input.Text()]++
|
||||
}
|
||||
|
||||
// NOTE: ignoring potential errors from input.Err()
|
||||
for line, n := range counts {
|
||||
if n > 1 {
|
||||
fmt.Printf("%d\t%s\n", n, line)
|
||||
}
|
||||
}
|
||||
}
|
15
lectures/00-intro/echo.go
Normal file
15
lectures/00-intro/echo.go
Normal file
|
@ -0,0 +1,15 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var s, sep string
|
||||
for i := 1; i < len(os.Args); i++ {
|
||||
s += sep + os.Args[i]
|
||||
sep = " "
|
||||
}
|
||||
fmt.Println(s)
|
||||
}
|
15
lectures/00-intro/echo2.go
Normal file
15
lectures/00-intro/echo2.go
Normal file
|
@ -0,0 +1,15 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
s, sep := "", ""
|
||||
for _, arg := range os.Args[1:] {
|
||||
s += sep + arg
|
||||
sep = " "
|
||||
}
|
||||
fmt.Println(s)
|
||||
}
|
40
lectures/00-intro/fetchall.go
Normal file
40
lectures/00-intro/fetchall.go
Normal file
|
@ -0,0 +1,40 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
start := time.Now()
|
||||
ch := make(chan string)
|
||||
for _, url := range os.Args[1:] {
|
||||
go fetch(url, ch) // start a goroutine
|
||||
}
|
||||
for range os.Args[1:] {
|
||||
fmt.Println(<-ch) // receive from channel ch
|
||||
}
|
||||
fmt.Printf("%.2fs elapsed\n", time.Since(start).Seconds())
|
||||
}
|
||||
|
||||
func fetch(url string, ch chan<- string) {
|
||||
start := time.Now()
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
ch <- fmt.Sprint(err) // send to channel ch
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close() // don't leak resources
|
||||
|
||||
nbytes, err := io.Copy(ioutil.Discard, resp.Body)
|
||||
if err != nil {
|
||||
ch <- fmt.Sprintf("while reading %s: %v", url, err)
|
||||
return
|
||||
}
|
||||
secs := time.Since(start).Seconds()
|
||||
ch <- fmt.Sprintf("%.2fs %7d %s", secs, nbytes, url)
|
||||
}
|
|
@ -79,3 +79,174 @@ Language
|
|||
Простой синтаксис (понятный для людей *и* машин).
|
||||
|
||||
Простая система типов. Объектно ориентированный, но без иерархий.
|
||||
|
||||
* Hello World
|
||||
|
||||
.play -edit helloworld.go
|
||||
|
||||
: Как запустить. В презентации и в CLI.
|
||||
: Что такое пакет.
|
||||
: Импорты. fmt - стандартная библиотека.
|
||||
: Пакет main.
|
||||
: Автоматическое форматирование.
|
||||
: goimports
|
||||
|
||||
* echo
|
||||
|
||||
.play -edit echo.go
|
||||
|
||||
: Слайсы. s[n:m], s[i], len(s).
|
||||
: var создаёт переменную. Инициализация zero value.
|
||||
|
||||
* For loop
|
||||
|
||||
Полная форма.
|
||||
|
||||
for initialization; condition; post {
|
||||
// statements
|
||||
}
|
||||
|
||||
Как while.
|
||||
|
||||
for condition {
|
||||
// statements
|
||||
}
|
||||
|
||||
Бесконечный цикл.
|
||||
|
||||
for {
|
||||
// statements
|
||||
}
|
||||
|
||||
* echo2
|
||||
|
||||
.play -edit echo2.go
|
||||
|
||||
* Range
|
||||
|
||||
Полная форма.
|
||||
|
||||
for i, v := range slice {
|
||||
// ...
|
||||
}
|
||||
|
||||
Только индекс.
|
||||
|
||||
for i := range slice {
|
||||
// ...
|
||||
}
|
||||
|
||||
Индекс не используется.
|
||||
|
||||
for _, v := range slice {
|
||||
// ...
|
||||
}
|
||||
|
||||
* Переменные
|
||||
|
||||
s := ""
|
||||
var s string
|
||||
var s = ""
|
||||
var s string = ""
|
||||
|
||||
* dup
|
||||
|
||||
.play -edit dup.go
|
||||
|
||||
: map. Создаётся через make(). Значения инициализируются нулём. Ключ должен иметь ==.
|
||||
: Итерация по map.
|
||||
: bufio.Scanner.
|
||||
: Printf.
|
||||
|
||||
* Printf
|
||||
|
||||
%d decimal integer
|
||||
%x, %o, %b integer in hexade cimal, octal, binary
|
||||
%f, %g, %e floating-point number: 3.141593 3.141592653589793 3.141593e+00
|
||||
%t boolean: true or false
|
||||
%c rune (Unicode code point)
|
||||
%s string
|
||||
%q quoted string "abc" or rune 'c'
|
||||
%v any value in a natural format
|
||||
%T type of any value
|
||||
%% literal percent sign (no operand)
|
||||
|
||||
Функции форматирования заканчиваются на `f`. `fmt.Errorf`, `log.Printf`.
|
||||
|
||||
* urlfetch
|
||||
|
||||
.code urlfetch.go /func main/,/^}/
|
||||
|
||||
* fetchall
|
||||
|
||||
.code fetchall.go /func main/,/^}/
|
||||
|
||||
* fetchall
|
||||
|
||||
.code fetchall.go /func fetch/,/^}/
|
||||
|
||||
* webserver
|
||||
|
||||
.code web.go
|
||||
|
||||
* webserver
|
||||
|
||||
.code counter.go
|
||||
|
||||
* switch
|
||||
|
||||
switch coinflip() {
|
||||
case "heads":
|
||||
heads++
|
||||
case "tails":
|
||||
tails++
|
||||
default:
|
||||
fmt.Println("landed on edge!")
|
||||
}
|
||||
|
||||
_tagless_ switch.
|
||||
|
||||
func Signum(x int) int {
|
||||
switch {
|
||||
case x > 0:
|
||||
return +1
|
||||
default:
|
||||
return 0
|
||||
case x < 0:
|
||||
return -1
|
||||
}
|
||||
}
|
||||
|
||||
* Other
|
||||
|
||||
Struct
|
||||
|
||||
type Point struct {
|
||||
X, Y int
|
||||
}
|
||||
var p Point
|
||||
|
||||
Pointers
|
||||
|
||||
var s string
|
||||
p := &s
|
||||
s2 = *p
|
||||
|
||||
var p Point
|
||||
p.X = 1
|
||||
|
||||
var pp *Point
|
||||
pp.X = 1
|
||||
|
||||
* The Go Programming Language
|
||||
|
||||
.image book.jpg
|
||||
|
||||
Всего 400 страниц.
|
||||
|
||||
* Документация
|
||||
|
||||
.link https://golang.org/doc/effective_go.html Effective Go
|
||||
.link https://golang.org/pkg/ Документация стандартной библиотеки
|
||||
.link https://golang.org/doc/faq Go FAQ
|
||||
.link https://github.com/golang/go/wiki/CodeReviewComments Code Review Comments
|
||||
|
|
25
lectures/00-intro/urlfetch.go
Normal file
25
lectures/00-intro/urlfetch.go
Normal file
|
@ -0,0 +1,25 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
for _, url := range os.Args[1:] {
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "fetch: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
b, err := ioutil.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "fetch: reading %s: %v\n", url, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Printf("%s", b)
|
||||
}
|
||||
}
|
17
lectures/00-intro/web.go
Normal file
17
lectures/00-intro/web.go
Normal file
|
@ -0,0 +1,17 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func main() {
|
||||
http.HandleFunc("/", handler) // each request calls handler
|
||||
log.Fatal(http.ListenAndServe("localhost:8000", nil))
|
||||
}
|
||||
|
||||
// handler echoes the Path component of the request URL r.
|
||||
func handler(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
|
||||
}
|
Loading…
Reference in a new issue