《Go语言圣经》第一章 - 读书笔记

第一章 Go语言入门

01 Hello World

  • Go 是一门编译型语言(静态编译),Go语言的工具链将源代码及其依赖转换成计算机的机器指令

  • Go 语言提供的工具都通过一个单独的命令 go 调用

    • go 命令有一系列子命令,最简单的一个子命令就是 run,该命令编译一个或多个以 .go 结尾的源文件,链接库文件,并运行最终生成的可执行文件
    • build 子命令可以生成一个可执行的二进制文件,该编译结果可长期保存,之后可以随时运行它

    注意:

    1、Windows系统下生成的可执行文件是 helloworld.exe,增加了 .exe 后缀名

    2、Windows系统下在命令行可以直接输入helloworld.exe命令运行

    3、go build 生成的可执行文件是静态编译,不需要担心在系统库更新的时候会冲突

    4、静态编译和动态编译的区别

    ① 静态编译

    编译器在编译可执行文件时,把需要用到的对应的动态链接库(.so 或 .lib)中的部分提取出来,链接到可执行文件中,是可执行文件在运行时不需要依赖于动态链接库

    ② 动态编译

    动态编译的可执行文件需要附带一个的动态链接库,在执行时,需要调用其对应动态链接库中的命令。所以其优点有:

    • 缩小了执行文件本身的体积

    • 加快了编译速度,节省了系统资源

    其缺点有:

    • 即使是很简单的程序只用到了链接库中的一两条命令,也需要附带一个相对庞大的链接库
    • 如果其他计算机上没有安装对应的运行库,则用动态编译的可执行文件就不能运行
  • Go 语言原生支持 Unicode,它可以处理全世界任何语言的文本

举例:

package main

import "fmt"

func main()  {
	fmt.Println("Hello World!")
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2SzGmY09-1645002079788)(E:\Typora笔记\Golang学习\Golang基础\images\Untitled\image-20220207103042660.png)]

在这里插入图片描述
在这里插入图片描述

  • Go 语言的代码通过**包(package)**组织,包类似于其它语言里的库(libraries)或者模块(modules)

  • 一个包由位于单个目录下的一个或多个.go 源码文件组成,目录定义包的作用

  • 每个源文件都以一条package声明语句开始,表示该文件属于哪个包,紧跟着一系列导入import的包,之后是存储在这个文件里的程序语句

  • main包定义了一个独立可执行的程序,main包里的main函数是整个程序执行时的入口,main函数所做的事情就是程序做的,其一般是调用其它包里的函数完成很多工作

  • 跟随在package声明之后的import声明作用就是告诉编译器源文件需要哪些包

  • 必须恰当导入需要的包,缺少了必要的包或者导入了不需要的包,程序都无法编译通过。该项严格要求避免了程序开发过程中引入未使用的包

  • 跟随在import声明之后的是组成程序的函数、变量、常量、类型的声明语句(分别由关键字funcvarconsttype定义)

  • Go语言不需要再语句或者声明的末尾添加分号,除非一行上有多条语句

    • 实际上,编译器会主动把特定符号后的换行符转换为分号,因此换行符添加的位置会影响Go代码的正确解析

    • gofmt工具把代码格式化为标准格式

    • goimports工具可以根据代码需要自动的添加或删除import声明

      可用以下安装命令:

      go get golang.org/x/tools/cmd/goimports
      

02 命令行参数

  • os 包以跨平台的方式,提供了一些与操作系统交互的函数和变量,程序的命令行参数可从OS包的Args变量获取;os包外部使用os.Args访问改变量

    • os.Args变量是一个字符串的切片,其第一个元素 os.Args[0] 是命令本身的名字,其他的元素则是程序启动时传给它的参数
  • Go 语言中的注释语句以 // 开头

  • 按照惯例,我们在每个包的包声明前添加注释,对于main package,注释包含一句或几句话,从整体角度对程序做个描述

  • 变量会在声明时直接初始化,如果变量没有显式初始化,则被隐式地赋予其类型的零值

  • Go 语言只有for循环一种循环语句。for循环有多种形式,其中一种如下所示:

    for initialization; condition; post{
    // zero or more statements
    }
    
    • for 循环三个部分不需要括号包围。大括号强制要求,左大括号必须和post语句在同一行

    • initialization语句是可选的,在循环开始前执行。initialization语句如果存在,必须是一条简单语句,即,短变量声明、自增语句、赋值语句或函数调用

    • for 循环的三个部分每个都可以省略

      • 如果省略 initialization 和 post,分号也可以省略:
      // a traditional "while" loop
      for condition {
          // ...
      }
      
      • 如果连 condition 也省略就变成无限循环,可用 breakreturn 语句终止循环
      // a traditional infinite loop
      for {
          // ...
      }
      
    • for 循环的另外一种形式是在某种类型的区间(range)上遍历,如字符串或切片

      package main
      
      import (
      	"fmt"
      	"os"
      )
      
      func main()  {
      	s, sep := "", ""
      	for _, arg := range os.Args[1:] {
      		s += sep + arg
      		sep = " "
      	}
      	fmt.Println(s)
      }
      
      • 每次循环迭代,range 产生一对值:索引以及在该索引处的元素值,range 的语法要求是要处理元素就必须处理索引,如果索引无用处,Go语言的解决方法是使用**空标识符**,即 _
      • 空标识符可用于在任何语法需要变量名但程序逻辑不需要的时候,如在循环里丢弃不需要的循环索引,并保留元素值
  • 变量声明的方式:

    s := ""
    var s string
    var s = ""
    var s string = ""

    第 ① 种是短变量声明,最简洁,但只能用在函数内部,而不能用于包变量

    第 ② 种形式依赖于字符串的默认初始化零值机制,被初始化为 “”

    第 ③ 种形式用的很少,除非同时声明多个变量

    第 ④ 种显式的标明变量的类型,当变量类型与初值类型相同时,类型冗余,但如果两者类型不同,变量类型就必须了

    具体实践中一般使用 ① ②两种,初始值重要的话就显式的指定变量类型,否则使用隐式初始化

  • 使用 strings 包的 Join 函数拼接字符串:

    func main()  {
    	fmt.Println(strings.Join(os.Args[1:], " "))
    }
    

练习

echo 程序

// Echo1 prints its command-line arguments.
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)
}
练习1.1

修改 echo 程序,使其能够打印 os.Args[0],即被执行命令本身的名字

func main()  {
	fmt.Println(os.Args[0])
}
练习1.2:

修改 echo 程序,使其打印每个参数的索引和值,每个一行

package main

import (
	"fmt"
	"os"
)

func main()  {
	s, sep := "", ""
	for index, arg := range os.Args[1:] {
		s += sep + strconv.Itoa(index) + " " + arg
		sep = "\n"
	}
	fmt.Println(s)
}
  • Go 语言中 int 类型转 string 类型的方法:

    package main
    
    import (
    	"fmt"
    	"strconv"
    )
    
    var i int = 10
    
    func main() {
    	// ① 通过 Itoa 方法转换
    	str1 := strconv.Itoa(i)
    
    	// ② 通过 Sprintf 方法转换 %d代表Integer
    	str2 := fmt.Sprintf("%d", i)
    
    	// 打印str1
    	fmt.Println(str1)
    	// 打印str2
    	fmt.Println(str2)
    }
    
练习1.3:

做实验测量潜在低效的版本和使用了 strings.Join 的版本的运行时间差异

03 查找重复的行

  • 对文件做拷贝、打印、搜索、排序、统计或类似事情的程序都有一个差不多的程序结构:

    • 一个处理输入的循环
    • 在每个元素上执行计算处理
    • 在处理的同时或最后产生输出
  • Go 语言的 map 存储了键/值(key/value)的集合,对集合元素提供常数时间的存、取或测试操作,其键key可以是任意类型,只要其值value能用 == 运算符比较即可,内置函数make创建空map

    // map             key    value
    counts := make(map[string]int)
    
    • Go 的 map 类似于 Java 中的 HashMap、Python 中的 dict
    • map 的迭代顺序并不确定,从实践来看,该顺序随机,每次运行都会变化
  • bufio 包可用来处理输入和输出,其中的 Scanner 类型可以读取输入并将其拆成行或单词,通常是处理行形式的输入最简单的方法

    • 创建 bufio.Scanner 类型的变量 input ,每次调用 input.Scan(),即读入下一行,并移除行末的换行符,其读取的内容可以调用 input.Text() 得到,Scan 函数在读到一行时返回 true,不再有输入时返回 false
  • 程序读取数据的方式:

    • 从标准输入中读取数据,os.Stdin 指程序的标准输入
    • 从一系列具名文件中读取数据,os.Open 打开各个具名文件,os.Open 函数返回两个值
      • 第一个值是被打开的文件(*os.File),其后被 Scanner 读取
      • 第二个值是内置 error 类型的值,如果 err 等于内置值 nil(相当于其它语言里的NULL),那么文件被成功打开;如果 err 的值不是 nil,说明打开文件时出错了
  • fmt.Printf 函数对一些表达式产生格式化输出,该函数的首个参数是格式字符串,用于指定后续参数被如何格式化,各个参数的格式取决于转换字符,其形式为百分号后跟一个字母,规范举例:

    转换字符意义
    %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变量的类型
    %%字面上的百分号标志(无操作数)
    • 转义字符:制表符 \t和换行符 \n
  • 函数和包级别的变量可以任意顺序声明,并不影响其被调用,但最好还是遵循一定的规范

  • map 是一个由 make 函数创建的数据结构的引用,map 作为参数传递给某函数时,该函数接受这个引用的一份拷贝,被调用函数对 map 底层数据结构的任何修改,调用者函数都可以通过持有的 map 引用看到,类似于C++里的引用传递,实际上指针是另一个指针了,但内部存的值指向同一块内存

  • dup的前两个版本以"流”模式读取输入 ,并根据需要拆分成多个行。理论上,这些程序可以处理任意数量的输入数据

    • 另一个方法:一次性读取全部输入数据到内存中,然后一次分割为多行,再处理它们
  • io/ioutil包的ReadFile函数读取指定文件的全部内容,该函数返回一个字节切片(byte slice),必须将其转换为 string,才能用 strings.Split分割

  • strings.Split函数把字符串分割成字串的切片

  • bufio.Scannerioutil.ReadFileioutil.WriteFile都使用*os.FileReadWrite方法,但程序员很少需要直接调用低级函数,高级函数,像bufio.Scannerioutil.ReadFile包中所提供的那些,用起来要容易点

例子运行

dup1
package main

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

func main()  {
	counts := make(map[string]int)
	// 测试读取标准输入使用 Ctrl+D 结束输入
	input := bufio.NewScanner(os.Stdin)
	for input.Scan() {
		counts[input.Text()]++
		// line := input.Text()
		// counts[line] = counts[line]+1
	}

	for line, n := range counts {
		if n > 1 {
			fmt.Printf("%d\t%s\n", n, line)
		}
	}
}

运行示例:
在这里插入图片描述

dup2
package main

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

// 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.
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()
}

运行示例:
在这里插入图片描述

dup3
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)
		}
	}
}

运行示例:
在这里插入图片描述

练习

练习1.4:

修改dup2,出现重复的行时打印文件名称

package main

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

type LnFile struct {
	Count int
	FileNames []string
}

// 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.
func main()  {
	counts := make(map[string]*LnFile)
	files := os.Args[1:]
	if len(files) == 0 {
		countLine(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
			}
			countLine(f, counts)
			f.Close()
		}
	}
	for line, n := range counts {
		if n.Count > 1 {
			fmt.Printf("%d\t%v\t%s\n", n.Count, n.FileNames, line)
		}
	}
}

func countLine(f *os.File, counts map[string]*LnFile)  {
	input := bufio.NewScanner(f)
	for input.Scan() {
		key := input.Text()
		_, ok := counts[key]
		if ok {
			counts[key].Count++
			counts[key].FileNames = append(counts[key].FileNames, f.Name())
		} else {
			counts[key] = new(LnFile)
			counts[key].Count = 1
			counts[key].FileNames = append(counts[key].FileNames, f.Name())
		}
	}
	// NOTE: ignoring potential errors from input.Err()
}

在这里插入图片描述

04 GIF 动画

  • 当我们import了一个包路径包含有多个单词的package时,比如image/color(image和color两个单词),通常我们只需要用最后那个单词表示这个包就可以
  • 常量是指在程序变异后运行时始终都不会变化的值
    • 常量声明和变量声明一般都会出现在包级别,所以这些常量在整个包中都是可以共享的
    • 常量声明也可以定义在函数体内部,此时常量只能在函数体内用
    • 目前常量声明的值必须是一个数字值、字符串或者一个固定的boolean值
  • struct 是一组值或者叫字段的集合,不同的类型集合在一个struct可以让我们以一个统一的单元进行处理
package main

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

// 利萨如图形

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

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

func main() {
	// The sequence of images is deterministic unless we seed
	// the pseudo-random number generator using the current time.
	// 图像序列是确定的,除非我们使用当前时间播种伪随机数生成器
	rand.Seed(time.Now().UTC().UnixNano())
	// 按照书中代码运行编码生成的GIF无法正常打开,改为直接输出字节文件就可以了
	// 目测是因为windows环境转了一些控制字符
	buf := &bytes.Buffer{}
	lissajous(buf)
	if err := ioutil.WriteFile("output.gif", buf.Bytes(), 0666); err != nil {
		panic(err)
	}
}

func lissajous(out io.Writer)  {
	const (
		cycles = 5 // number of complete x oscillator revolutions 完成x振子转数
		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 帧间延迟以10ms为单位
	)

	freq := rand.Float64() * 3.0 // relative frequency of y osillator y振荡器的相对频率
	anim := gif.GIF{LoopCount: nframes}
	phase := 0.0 // phase diffrence 相位差
	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) // ignoring encoding errors
}

请添加图片描述

练习

练习1.5:

修改前面的Lissajous程序里的调色板,由黑色改为绿色。我们可以用 color.RGBA{0xRR, 0xGG, 0xBB, 0xff}来得到 #RRGGBB 的色值,三个十六进制的字符串分别代表红、绿、蓝像素

var palette = []color.Color{color.RGBA{ 0, 0, 0, 0xFF}, color.RGBA{ 0, 0xFF, 0, 0xFF}}

请添加图片描述

练习1.6:

修改Lissajous程序,修改其调色板来生成更丰富的颜色,然后修改SetColorIndex的第三个参数,看看显示结果吧

package main

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

const nColors = 10

func main() {
	seed := time.Now()
	rand.Seed( seed.Unix() )

	var palette []color.Color

	for i := 0; i < nColors; i++ {
		r := uint8(rand.Uint32() % 256)
		g := uint8(rand.Uint32() % 256)
		b := uint8(rand.Uint32() % 256)
		palette = append( palette, color.RGBA{ r, g, b, 0xFF} )
	}

	buf := &bytes.Buffer{}
	lissajous1(buf, palette)
	if err := ioutil.WriteFile("output2.gif", buf.Bytes(), 0666); err != nil {
		panic(err)
	}
}

func lissajous1(out io.Writer, palette []color.Color) {
	const (
		cycles  = 5
		res     = 0.001
		size    = 100
		nframes = 64
		delay   = 8
	)
	freq := rand.Float64() * 3.0
	anim := gif.GIF{LoopCount: nframes}
	phase := 0.0
	for i := 0; i < nframes; i++ {
		rect   := image.Rect(0, 0, 2*size+1, 2*size+1)
		img    := image.NewPaletted(rect, palette)
		ncolor := uint8(i % len(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), ncolor )
		}
		phase += 0.1
		anim.Delay = append(anim.Delay, delay)
		anim.Image = append(anim.Image, img)
	}
	gif.EncodeAll(out, &anim)
}

请添加图片描述

05 获取URL

  • http.Get 函数是创建HTTP请求的函数
    • 如果获取过程没有出错,其得到的访问的请求结果的Body字段包括一个可读的服务器响应流,利用ioutil.ReadAll函数可以读取Body字段中的全部内容
    • Body.Close关闭Body流,防止资源泄露
  • os.Exit函数终止进程,并且返回一个status错误码,其值为1
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)
		}
		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)
	}
}

在这里插入图片描述

练习

练习1.7:

函数调用io.Copy(dst, src)会从src中读取内容,并将读到的结果写入到dst中,使用这个函数替代例子中的ioutil.ReadAll来拷贝响应结构体到os.Stdout,避免申请一个缓冲区来存储,记得处理io.Copy返回结果中的错误

package main

import (
	"fmt"
	"io"
	"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)
		}
		//b, err := ioutil.ReadAll(resp.Body)
		//        io.Copy(dst Writer, src Reader)
		b, err := io.Copy(os.Stdout, resp.Body)
		resp.Body.Close()
		if err != nil {
			//fmt.Fprintf(os.Stderr, "fetch: reading %s: %v\n", url, err)
			fmt.Fprintf(os.Stderr, "fetch: %v\n", err)
			os.Exit(1)
		}
		fmt.Printf("%s", b)
	}
}
练习1.8:

修改fetch这个范例,如果输入的url参数没有http://前缀的话,为这个url加上该前缀。你可能会用到strings.HasPrefix这个函数。

package main

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

func main()  {
	for _, url := range os.Args[1:] {
        // strings.HasPrefix
		if !strings.HasPrefix(url, "http://") {
			url = strings.Join([]string{"http://", url}, "")
		}
		resp, err := http.Get(url)
		if err != nil {
			fmt.Fprintf(os.Stderr, "fetch: %v\n", err)
		}
		//        io.Copy(dst Writer, src Reader)
		b, err := io.Copy(os.Stdout, resp.Body)
		resp.Body.Close()
		if err != nil {
			fmt.Fprintf(os.Stderr, "fetch: %v\n", err)
			os.Exit(1)
		}
		fmt.Printf("%s", b)
	}
}

在这里插入图片描述

练习1.9:

修改fetch打印出HTTP协议的状态码,可以从resp.Status变量得到该状态码

package main

import (
	"fmt"
	"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)
		}
		b := resp.Status
		fmt.Printf("%s", b)
	}
}

在这里插入图片描述

06 并发获取多个URL

  • goroutine是一种函数的并发执行方式,而channel是用来在goroutine之间进行参数传递
  • main函数本身也运行在一个goroutine中,而go function则表示创建一个新的goroutine,并在这个新的goroutine中执行这个函数
  • 当一个goroutine尝试在一个channel上做send或者receive操作时,这个goroutine会阻塞在调用处,直到另一个goroutine从这个channel里接收或者写入值,这样两个goroutine才会继续执行channel操作之后的逻辑
  • 每一个fetch函数在执行时都会往channel里发送一个值(ch <- expression),主函数负责接收这些值(<-ch),程序用main函数来接收所有fetch函数传回的字符串,可以避免在goroutine异步执行还没有完成时main函数提前退出
// 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)
	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)
}

在这里插入图片描述

练习

练习1.10:

找一个数据量比较大的网站,用本小节中的程序调研网站的缓存策略,对每个URL执行两遍请求,查看两次时间是否有较大的差别,并且每次获取到的响应内容是否一致,将响应结果输出,以便于进行对比

// 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
		go fetch(url, ch) // start a goroutine
	}
	for range os.Args[1:] {
		fmt.Println(<-ch) // receive from channel ch
		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)
	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)
}

在这里插入图片描述

练习1.11:

在fetchall中尝试使用长一些的参数列表,比如使用在alexa.com的上百万网站里排名靠前的,如果一个网站没有回应,程序将采取怎样的行为?

07 Web服务

  • main函数将所有发送到/路径下的请求和handler函数关联起来
    • /开头的请求就是所有发送到当前站点上的请求,服务监听8000端口
    • 发送到这个服务的“请求”是一个http.Request类型的对象,这个对象中包含了请求中的一系列相关字段
    • 当请求到达服务器时,这个请求会被传给handler函数来处理

server1

// 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)
}

在这里插入图片描述

server2

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:8001", nil))
}

// handler echoes the Path component of the requested URL
func Handler(w http.ResponseWriter, r *http.Request) {
	// 上锁
	mu.Lock()
	// 避免同一时刻两个请求去更新count
	count++
	// 保证每次修改变量的最多只有一个goroutine
	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()
}

在这里插入图片描述

server3

package main

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

func main() {
	http.HandleFunc("/", HandLer)
	log.Fatal(http.ListenAndServe("localhost:8001", nil))
}

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)
	}
	// %q 带双引号的字符串"abc" 或 带单引号的 rune 'c'
	fmt.Fprintf(w, "Host = %q\n", r.RemoteAddr)
	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)
	}
}

在这里插入图片描述

练习

练习1.12:

修改Lissajour服务,从URL读取变量,比如你可以访问http://localhost:8000/?cycles=20 这个URL,这样访问可以将程序里的cycles默认的5修改为20。字符串转换为数字可以调用strconv.Atoi函数。你可以在godoc里查看strconv.Atoi的详细说明

package main

import (
	"image"
	"image/color"
	"image/gif"
	"io"
	"log"
	"math"
	"math/rand"
	"net/http"
	"strconv"
	"time"
)

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

const (
	whiteIndex = 0
	blackIndex = 1
)

type lconfig struct {
	cycles float64
	res    float64
	freq   float64
	size   int
	frames int
	delay  int
}

func main() {
	rand.Seed(time.Now().UnixNano())
	lconf := lconfig{
		cycles: 5,
		res:    0.001,
		freq:   rand.Float64() * 3.0,
		size:   100,
		frames: 64,
		delay:  8,
	}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		confs := r.URL.Query()
		for i, c := range confs {
			switch i {
			case "cycles":
				lconf.cycles, _ = strconv.ParseFloat(c[0], 64)
			case "freq":
				lconf.freq, _ = strconv.ParseFloat(c[0], 64)
			case "res":
				lconf.res, _ = strconv.ParseFloat(c[0], 64)
			case "size":
				lconf.size, _ = strconv.Atoi(c[0])
			case "frames":
				lconf.frames, _ = strconv.Atoi(c[0])
			case "delay":
				lconf.delay, _ = strconv.Atoi(c[0])
			}
		}

		lissajous(w, lconf)
	})

	log.Fatal(http.ListenAndServe("localhost:8000", nil))
	return
}

func lissajous(out io.Writer, set lconfig) {
	anim := gif.GIF{LoopCount: set.frames}
	phase := 0.0 // phase difference
	for i := 0; i < set.frames; i++ {
		rect := image.Rect(0, 0, 2*set.size+1, 2*set.size+1)
		img := image.NewPaletted(rect, palette)
		for t := 0.0; t < set.cycles*2*math.Pi; t += set.res {
			x := math.Sin(t)
			y := math.Sin(t*set.freq + phase)
			img.SetColorIndex(set.size+int(x*float64(set.size)+0.5), set.size+int(y*float64(set.size)+0.5), blackIndex)
		}
		phase += 0.1
		anim.Delay = append(anim.Delay, set.delay)
		anim.Image = append(anim.Image, img)
	}
	gif.EncodeAll(out, &anim)
}

08 本章要点

控制流

  • if

  • for

  • switch

    switch coinflip() {
        case "heads":
        	heads++
        case "tails":
        	tails++
        default:
        fmt.Println("landed on edge!")
    }
    
    • Go 语言并不需要显式地在每一个case后写break,其默认执行完case后的逻辑语句会自动退出

    • Go 语言里的switch还可以不带操作对象,这时默认用true值代替,然后将每个case的表达式和true值进行比较,可以直接罗列各种条件,该形式叫做无tag switch,等价于 switch true

      switch {
      	case x > 0 :
          	return +1
          default:
          	return 0
      }
      
    • 像for和if控制语句一样,switch也可以紧跟一个简短的变量声明,一个自增表达式、赋值语句,或者一个函数调用

  • break 会中断当前的循环,并开始执行循环之后的内容

  • continue 会跳过当前循环,并开始执行下一次循环

命名类型

  • 类型声明使得我们可以很方便地给一个特殊类型一个名字

    type Point struct {
        X, Y int
    }
    

指针

  • 指针是一种直接存储了变量的内存地址的数据类型
    • Go 语言中指针是可见的内存地址,但是在Go 语言里没有指针运算
    • &操作符可以返回一个变量的内存地址
    • *操作符可以获取指针指向的变量内容

方法和接口

  • 方法是和命名类型关联的一类函数
  • Go 语言里比较特殊的就是方法可以被关联到任意一种命名类型
  • 接口是一种抽象类型,其可以让我们以同样的方式来处理不同的固有类型,不用关心它们的具体实现而只需要关注它们提供的方法

包(packages)

  • Go 语言里有一些很好用的package,并且这些package是可以扩展的

  • 在写一个新程序之前可以先去检查一下是否存在现成的库可以帮助你更高效地完成这件事情

注释

  • 源文件的开头写的注释是该源文件的文档
  • 每一个函数之前写一个说明函数行为的注释
  • 多行注释可以用 /* ... */ 来包裹,在文件一开头的注释一般都是这种形式,或者一大段的解释性的注释文字也会使用多行注释,从而避免每一行都需要加//
  • 在注释中 ///* 没有什么意义,因此不要在注释中再嵌入注释
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爪喵喵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值