命令行参数接收

  1. 普通方法
1
2
3
4
5
6
var s, sep string
for i := 1; i < len(os.Args); i++ {
s += sep + os.Args[i]
sep = " "
}
fmt.Println(s)
  1. 使用range

range产生一对值:索引以及在该索引处的元素值

1
2
3
4
5
6
s, sep := "", ""
for _, arg := range os.Args[1:] {
s += sep + arg
sep = " "
}
fmt.Println(s)

Go语言不允许使用无用的局部变量(local variables),因为这会导致编译错误。

变量声明
1
2
3
4
s := ""
var s string
var s = ""
var s string = ""
  • 第一种形式: 短变量声明
    • 最简洁,但只能用在函数内部,而不能用于包变量。
  • 第二种形式
    • 依赖于字符串的默认初始化零值机制,被初始化为""
  • 第三种形式
    • 用得很少,除非同时声明多个变量。
  • 第四种形式
    • 显式地标明变量的类型,当变量类型与初值类型相同时,类型冗余,
    • 但如果两者类型不同,变量类型就必须了
  1. 简洁高效的方法,使用strings
1
2
3
func main() {
fmt.Println(strings.Join(os.Args[1:], " "))
}

查找重复行

Dup1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Dup1 prints the text of each line that appears more than
// once in the standard input, preceded by its count.
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)
}
}
}
IF语句
  • if语句条件两边也不加括号,但是主体部分需要加
  • if语句的else部分是可选的,在if的条件为false时执行。
map
  • map存储了键/值(key/value)的集合,对集合元素,提供常数时间的存、取或测试操作。
    • 键可以是任意类型,只要其值能用==运算符比较,最常见的例子是字符串
    • 值则可以是任意类型。这个例子中的键是字符串,值是整数
    • 从功能和实现上说,Gomap类似于Java语言中的HashMap,Python语言中的dict
  • map的迭代顺序并不确定,从实践来看,该顺序随机,每次运行都会变化。
    • 这种设计是有意为之的,因为能防止程序依赖特定遍历顺序,而这是无法保证的。

每次读取一行输入,该行被当做键存入map,其对应的值递增。

counts[input.Text()]++语句等价下面两句:

1
2
line := input.Text()
counts[line] = counts[line] + 1
bufio
  • 它使处理输入和输出方便又高效。
  • Scanner类型是该包最有用的特性之一,它读取输入并将其拆成行或单词;
    • 通常是处理行形式的输入最简单的方法。
    • 每次调用input.Scan(),即读入下一行,并移除行末的换行符
    • 读取的内容可以调用input.Text()得到
    • Scan函数在读到一行时返回true,不再有输入时返回false
Printf
1
2
3
4
5
6
7
8
9
10
%d          十进制整数
%x, %o, %b 十六进制,八进制,二进制整数。
%f, %g, %e 浮点数: 3.141593 3.141592653589793 3.141593e+00
%t 布尔:true或false
%c 字符(rune) (Unicode码点)
%s 字符串
%q 带双引号的字符串"abc"或带单引号的字符'c'
%v 变量的自然形式(natural format)
%T 变量的类型
%% 字面上的百分号标志(无操作数)

Dup2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Dup2 prints the count and text of lines that appear more than once
// in the input. It reads from stdin or from a list of named files.
package main

import (
"bufio"
"fmt"
"os"
)

func main() {
counts := make(map[string]int)
files := os.Args[1:]

// 如果命令行参数中没有文件参数,则按输入来进行计数
if len(files) == 0 {
countLines(os.Stdin, counts)
} // 读取文件
else {
// 遍历所有参数
for _, arg := range files {
// 打开文件
f, err := os.Open(arg)
if err != nil {
fmt.Fprintf(os.Stderr, "dup2: %v\n", err)
continue
}
countLines(f, counts)
// 关闭文件
f.Close()
}
}
for line, n := range counts {
if n > 1 {
fmt.Printf("%d\t%s\n", n, line)
}
}
}

func countLines(f *os.File, counts map[string]int) {
input := bufio.NewScanner(f)
for input.Scan() {
counts[input.Text()]++
}
// NOTE: ignoring potential errors from input.Err()
}
os.Open函数
  • 返回两个值
    • 第一个值是被打开的文件(*os.File
    • 第二个值是内置error类型的值
注意
  • countLines函数在其声明前被调用。
  • 函数和包级别的变量(package-level entities)可以任意顺序声明,并不影响其被调用
map的变化
  • map是一个由make函数创建的数据结构的引用
  • map作为参数传递给某函数时,该函数接收这个引用的一份拷贝(copy,或译为副本)
  • 被调用函数对map底层数据结构的任何修改,调用者函数都可以通过持有的map引用看到

Dup3

dup的前两个版本以"流”模式读取输入,并根据需要拆分成多个行

可以一口气把全部输入数据读到内存中,一次分割为多行,然后处理它们。

  • 引入了ReadFile函数(来自于io/ioutil包),其读取指定文件的全部内容,
  • strings.Split函数把字符串分割成子串的切片
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package main

import (
"fmt"
"io/ioutil"
"os"
"strings"
)

func main() {
counts := make(map[string]int)
for _, filename := range os.Args[1:] {
data, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Fprintf(os.Stderr, "dup3: %v\n", err)
continue
}
for _, line := range strings.Split(string(data), "\n") {
counts[line]++
}
}
for line, n := range counts {
if n > 1 {
fmt.Printf("%d\t%s\n", n, line)
}
}
}
ReadFile函数

返回一个字节切片(byte slice),必须把它转换为string,才能用strings.Split分割。

注意

bufio.Scannerioutil.ReadFileioutil.WriteFile都使用*os.FileReadWrite方法

练习

出现重复的行打印文件名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package main

import (
"bufio"
"fmt"
"os"
)

func main() {
counts := make(map[string]int)
file := os.Args[1:]
if len(file) == 0 {
countLines1(os.Stdin, counts)
} else {
countFile := make(map[string]int)
for _, filename := range file {
data, err := os.Open(filename)
if err != nil {
fmt.Printf("error %v", err)
}
countLines(data, counts, filename, countFile)
}
for key, value := range countFile {
if value >= 1 {
fmt.Println(key, value)
}
}
}
// 出现重复的行时打印文件名称
}
func countLines1(f *os.File, counts map[string]int) {
input := bufio.NewScanner(f)
for input.Scan() {
counts[input.Text()]++
}
// NOTE: ignoring potential errors from input.Err()
}
func countLines(f *os.File, counts map[string]int, filename string, countFile map[string]int) {
input := bufio.NewScanner(f)
for input.Scan() {
counts[input.Text()]++
}
for _, value := range counts {
if value > 1 {
countFile[filename]++
}
}
// NOTE: ignoring potential errors from input.Err()
}

GIF动画--image包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Lissajous generates GIF animations of random Lissajous figures.
package main

import (
"image"
"image/color"
"image/gif"
"io"
"math"
"math/rand"
"os"
"time"
)

var palette = []color.Color{color.White, color.Black}

const (
whiteIndex = 0 // first color in palette
blackIndex = 1 // next color in palette
)

func main() {
// The sequence of images is deterministic unless we seed
// the pseudo-random number generator using the current time.
// Thanks to Randall McPherson for pointing out the omission.
rand.Seed(time.Now().UTC().UnixNano())
lissajous(os.Stdout)
}

func lissajous(out io.Writer) {
const (
cycles = 5 // number of complete x oscillator revolutions
res = 0.001 // angular resolution
size = 100 // image canvas covers [-size..+size]
nframes = 64 // number of animation frames
delay = 8 // delay between frames in 10ms units
)

freq := rand.Float64() * 3.0 // relative frequency of y oscillator
anim := gif.GIF{LoopCount: nframes}
phase := 0.0 // phase difference
for i := 0; i < nframes; i++ {
rect := image.Rect(0, 0, 2*size+1, 2*size+1)
img := image.NewPaletted(rect, palette)
for t := 0.0; t < cycles*2*math.Pi; t += res {
x := math.Sin(t)
y := math.Sin(t*freq + phase)
img.SetColorIndex(size+int(x*size+0.5), size+int(y*size+0.5),
blackIndex)
}
phase += 0.1
anim.Delay = append(anim.Delay, delay)
anim.Image = append(anim.Image, img)
}
gif.EncodeAll(out, &anim) // NOTE: ignoring encoding errors
}
  • import了一个包路径包含有多个单词的package时,比如image/color(image和color两个单词),通常我们只需要用最后那个单词表示这个包就可以
    • 当我们写color.White时,这个变量指向的是image/color包里的变量,同理gif.GIF是属于image/gif包里的变量

常量

  • 常量是指在程序编译后运行时始终都不会变化的值,比如圈数、帧数、延迟值
  • 常量声明和变量声明一般都会出现在包级别,所以这些常量在整个包中都是可以共享的,
  • 或者你也可以把常量声明定义在函数体内部,那么这种常量就只能在函数体内用

复合声明

  • []color.Color{...}和gif.GIF{...}这两个表达式就是我们说的复合声明
  • 前者生成的是一个slice切片,后者生成的是一个struct结构体。
    • struct是一组值或者叫字段的集合,不同的类型集合在一个struct可以让我们以一个统一的单元进行处理
    • anim是一个gif.GIF类型的struct变量。
    • 这种写法会生成一个struct变量,并且其内部变量LoopCount字段会被设置为nframes,其它的字段会被设置为各自类型默认的零值。
    • struct内部的变量可以以一个点(.)来进行访问

lissajous函数

  • 内部有两层嵌套的for循环

    • 外层循环会循环64次,每一次都会生成一个单独的动画帧
      • 生成了一个包含两种颜色的201*201大小的图片,白色和黑色
      • 所有像素点都会被默认设置为其零值(也就是调色板palette里的第0个值),这里我们设置的是白色。
      • 每次外层循环都会生成一张新图片,并将一些像素设置为黑色。
      • 结果会append到之前结果之后。这里我们用到了append(参考4.2.1)内置函数,将结果append到anim中的帧列表末尾,并设置一个默认的80ms的延迟值
      • 循环结束后所有的延迟值被编码进了GIF图片中,并将结果写入到输出流。
    • 内层循环设置两个偏振值。x轴偏振使用sin函数。y轴偏振也是正弦波,但其相对x轴的偏振是一个0-3的随机值,初始偏振值是一个零值,随着动画的每一帧逐渐增加
      • 循环会一直跑到x轴完成五次完整的循环。每一步它都会调用SetColorIndex来为(x,y)点来染黑色。
    • main函数调用lissajous函数,用它来向标准输出流打印信息
      1
      2
      go build gopl.io/ch1/lissajous
      lissajous >out.gif

获取URL--net包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Fetch prints the content found at a URL.
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)
}
}
  • http.Get函数是创建HTTP请求的函数,如果获取过程没有出错,那么会在resp这个结构体中得到访问的请求结果
    • resp的Body字段包括一个可读的服务器响应流
  • ioutil.ReadAll函数从response中读取到全部内容;将其结果保存在变量b中。
  • resp.Body.Close关闭resp的Body流,防止资源泄露,Printf函数会将结果b写出到标准输出流中。

练习

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Fetch prints the content found at a URL.
package main

import (
"fmt"
"io"
"net/http"
"os"
"strings"
)

func main() {
for _, url := range os.Args[1:] {
if !strings.HasPrefix(url,"https://") {
url = "https://"+url
}

resp, err := http.Get(url)
fmt.Println(resp.Status)
if err != nil {
fmt.Fprintf(os.Stderr, "fetch: %v\n", err)
os.Exit(1)
}

dst := io.Writer(os.Stdout)
_, err = io.Copy(dst, 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", os.Stdout)
}
}

并发获取多个URL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Fetchall fetches URLs in parallel and reports their times and sizes.
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
}
nbytes, err := io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close() // don't leak resources
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)
}
  • goroutine是一种函数的并发执行方式,而channel是用来在goroutine之间进行参数传递
  • main函数本身也运行在一个goroutine中,而go function则表示创建一个新的goroutine,并在这个新的goroutine中执行这个函数。
  • main函数中用make函数创建了一个传递string类型参数的channel
  • 对每一个命令行参数,我们都用go这个关键字来创建一个goroutine,并且让函数在这个goroutine异步执行http.Get方法
  • io.Copy会把响应的Body内容拷贝到ioutil.Discard输出流中
    • 可以把这个变量看作一个垃圾桶,可以向里面写一些不需要的数据),因为我们需要这个方法返回的字节数,但是又不想要其内容
  • 每当请求返回内容时,fetch函数都会往ch这个channel里写入一个字符串,由main函数里的第二个for循环来处理并打印channel里的这个字符串。
  • 当一个goroutine尝试在一个channel上做send或者receive操作时,这个goroutine会阻塞在调用处,直到另一个goroutine从这个channel里接收或者写入值,这样两个goroutine才会继续执行channel操作之后的逻辑

Web服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Server1 is a minimal "echo" server.
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)
}

对请求的次数进行计算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Server2 is a minimal "echo" and counter server.
package main

import (
"fmt"
"log"
"net/http"
"sync"
)

var mu sync.Mutex
var count int

func main() {
http.HandleFunc("/", handler)
http.HandleFunc("/count", counter)
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}

// handler echoes the Path component of the requested URL.
func handler(w http.ResponseWriter, r *http.Request) {
mu.Lock()
count++
mu.Unlock()
fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
}

// counter echoes the number of calls so far.
func counter(w http.ResponseWriter, r *http.Request) {
mu.Lock()
fmt.Fprintf(w, "Count %d\n", count)
mu.Unlock()
}

handler函数会把请求的http头和请求的form数据都打印出来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// handler echoes the HTTP request.
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s %s %s\n", r.Method, r.URL, r.Proto)
for k, v := range r.Header {
fmt.Fprintf(w, "Header[%q] = %q\n", k, v)
}
fmt.Fprintf(w, "Host = %q\n", r.Host)
fmt.Fprintf(w, "RemoteAddr = %q\n", r.RemoteAddr)
if err := r.ParseForm(); err != nil {
log.Print(err)
}
for k, v := range r.Form {
fmt.Fprintf(w, "Form[%q] = %q\n", k, v)
}
}

加入前面的gif

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Server2 is a minimal "echo" and counter server.
package main

import (
"fmt"
"image"
"image/color"
"image/gif"
"io"
"log"
"math"
"math/rand"
"net/http"
"sync"
)

var mu sync.Mutex
var count int

func main() {
http.HandleFunc("/", handler)
http.HandleFunc("/image", func(w http.ResponseWriter, r *http.Request) {
lissajous(w)
})
http.HandleFunc("/count", counter)
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}

// handler echoes the Path component of the requested URL.
// handler echoes the HTTP request.
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s %s %s\n", r.Method, r.URL, r.Proto)
for k, v := range r.Header {
fmt.Fprintf(w, "Header[%q] = %q\n", k, v)
}
fmt.Fprintf(w, "Host = %q\n", r.Host)
fmt.Fprintf(w, "RemoteAddr = %q\n", r.RemoteAddr)
if err := r.ParseForm(); err != nil {
log.Print(err)
}
for k, v := range r.Form {
fmt.Fprintf(w, "Form[%q] = %q\n", k, v)
}
}

// counter echoes the number of calls so far.
func counter(w http.ResponseWriter, r *http.Request) {
mu.Lock()
fmt.Fprintf(w, "Count %d\n", count)
mu.Unlock()
}

// Lissajous generates GIF animations of random Lissajous figures.

var palette = []color.Color{color.White, color.Black}

const (
whiteIndex = 0 // first color in palette
blackIndex = 1 // next color in palette
)

func lissajous(out io.Writer) {
const (
cycles = 5 // number of complete x oscillator revolutions
res = 0.001 // angular resolution
size = 100 // image canvas covers [-size..+size]
nframes = 64 // number of animation frames
delay = 8 // delay between frames in 10ms units
)

freq := rand.Float64() * 3.0 // relative frequency of y oscillator
anim := gif.GIF{LoopCount: nframes}
phase := 0.0 // phase difference
for i := 0; i < nframes; i++ {
rect := image.Rect(0, 0, 2*size+1, 2*size+1)
img := image.NewPaletted(rect, palette)
for t := 0.0; t < cycles*2*math.Pi; t += res {
x := math.Sin(t)
y := math.Sin(t*freq + phase)
img.SetColorIndex(size+int(x*size+0.5), size+int(y*size+0.5),
blackIndex)
}
phase += 0.1
anim.Delay = append(anim.Delay, delay)
anim.Image = append(anim.Image, img)
}
gif.EncodeAll(out, &anim) // NOTE: ignoring encoding errors
}