Go语言圣经练习解答-入门(第一章)

Go语言圣经练习解答-入门(第一章)

练习 1.1

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

package main

import (
	"fmt"
	"os"
	"strings"
)

func main() {
	fmt.Println(strings.Join(os.Args, " "))
}

练习 1.2

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

package main

import (
	"fmt"
	"os"
)

func main() {
	for index, value := range os.Args {
		fmt.Println(index, value)
	}
}

练习 1.3

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

package main

import (
	"strings"
	"testing"
)

func Benchmark1(b *testing.B) {
	for i := 0; i < b.N; i++ {
		input := []string{"12", "qw", "as", "zx"}
		strings.Join(input, " ")
	}
}

func Benchmark2(b *testing.B) {
	for i := 0; i < b.N; i++ {
		input := []string{"12", "qw", "as", "zx"}
		var result, sep string
		for _, value := range input {
			result += sep + value
			sep = " "
		}
	}
}

结果:

goos: darwin
goarch: amd64
Benchmark1
Benchmark1-4   	17314023	        64.9 ns/op
Benchmark2
Benchmark2-4   	 8261440	       148 ns/op
PASS

含义:
Benchmark1-4 17314023 64.9 ns/op

  • -4表示4个cpu线程执行
  • 17314023表示执行了17314023次
  • 64.9 ns/op表示每次执行耗时64.9纳秒
  • 所以使用strings.Join的方案比循环增加的方法更快

练习 1.4

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

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() {
		line := input.Text()
		counts[line]++
		if counts[line] > 1 {
			fmt.Println("dup:", line, f.Name())
		}
	}
	// NOTE: ignoring potential errors from input.Err()
}

练习 1.5,1.6

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

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

package main

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

//!-main
// Packages not needed by version in book.
import (
	"log"
	"net/http"
	"time"
)

//!+main

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

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

func main() {
	//!-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())

	if len(os.Args) > 1 && os.Args[1] == "web" {
		//!+http
		handler := func(w http.ResponseWriter, r *http.Request) {
			lissajous(w)
		}
		http.HandleFunc("/", handler)
		//!-http
		log.Fatal(http.ListenAndServe("localhost:8000", nil))
		return
	}
	//!+main
	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),
				uint8(rand.Intn(7)))
		}
		phase += 0.1
		anim.Delay = append(anim.Delay, delay)
		anim.Image = append(anim.Image, img)
	}
	gif.EncodeAll(out, &anim) // NOTE: ignoring encoding errors
}

练习 1.7,1.8,1.9

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

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

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

package main

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

func main() {
	for _, url := range os.Args[1:] {
		// 练习1.8
		if !strings.HasPrefix(url, "http://") {
			url = "http://" + url
		}
		resp, err := http.Get(url)
		if err != nil {
			fmt.Fprintf(os.Stderr, "fetch: %v\n", err)
			os.Exit(1)
		}
		// 练习1.7
		_, err = io.Copy(os.Stdout, resp.Body)
		resp.Body.Close()
		if err != nil {
			fmt.Fprintf(os.Stderr, "fetch: reading %s: %v\n", url, err)
			os.Exit(1)
		}
		// 练习1.9
		fmt.Println("Status Code: ", resp.Status)
	}
}

练习 1.10,1.11

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

在fetchall中尝试使用长一些的参数列表,比如使用在alexa.com的上百万网站里排名靠前的。如果一个网站没有回应,程序将采取怎样的行为?(Section8.9 描述了在这种情况下的应对机制)。

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

结果:

0.04s       81  http://baidu.com
0.04s       81  http://baidu.com
Get "http://google.com": read tcp 192.168.2.191:59327->93.46.8.90:80: read: connection reset by peer
0.13s     6632  http://192.168.2.254
0.13s     6632  http://192.168.2.254
0.27s   119146  http://jd.com
0.27s   119146  http://jd.com
0.30s   215284  http://sohu.com
0.30s   215284  http://sohu.com
0.30s    81462  http://360.cn
0.30s    81462  http://360.cn
0.34s   121866  http://taobao.com
0.35s   121866  http://taobao.com
0.37s   141808  http://tmall.com
0.38s   101564  http://qq.com
0.39s   101564  http://qq.com
0.51s   141808  http://tmall.com
Get "http://google.com": dial tcp 93.46.8.90:80: i/o timeout
30.00s elapsed

两次google.com的请求分别报了不同的错

  • tcp read: connection reset by peer
  • i/o timeout

练习 1.12

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

访问:http://localhost:8000/gif?c=5

package main

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

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

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

func main() {
	http.HandleFunc("/", handler)       // each request calls handler
	http.HandleFunc("/gif", gifhandler) // each request calls handler
	log.Fatal(http.ListenAndServe("localhost:8000", nil))
}

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

func gifhandler(w http.ResponseWriter, r *http.Request) {
	params := r.URL.Query()
	fmt.Println(params)
	cStr := params.Get("c")
	cInt, _ := strconv.Atoi(cStr)
	lissajous(w, float64(cInt))
}

func lissajous(out io.Writer, c float64) {
	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 < c*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),
				uint8(rand.Intn(7)))
		}
		phase += 0.1
		anim.Delay = append(anim.Delay, delay)
		anim.Image = append(anim.Image, img)
	}
	gif.EncodeAll(out, &anim) // NOTE: ignoring encoding errors
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

苏打呀

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

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

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

打赏作者

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

抵扣说明:

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

余额充值