《GO语言圣经》读书笔记 第一章 习题解答

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

package main

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

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

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

package main

import (
    "os"
    "fmt"
)

func main() {

    for index,arg := range os.Args[1:]{
        fmt.Println(index+1,":",arg)
    }
}

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

package main

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

func main() {
    joinEcho()
    plusEcho()
}

func joinEcho(){
    start := time.Now();
    fmt.Println(strings.Join(os.Args[1:]," "))
    fmt.Printf("echo2: %fs\n",time.Since(start).Seconds())
}

func plusEcho(){
    start := time.Now()
    s,sep := "",""
    for _,arg := range os.Args[1:]{
        s += sep + arg
        sep = " "
    }
    fmt.Println(s)

    fmt.Printf("plushEcho: %fs\n",time.Since(start).Seconds())
}

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

package main

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

func main() {
    counts := make(map[string]int)
    fileNames := make(map[string][]string)
    files := os.Args[1:]
    if len(files) == 0 {
        countLines(os.Stdin,counts,fileNames)
    }else{
        for _,file := range files {
            f, e := os.Open(file)
            if e != nil {
                fmt.Fprintf(os.Stderr,"dup : %v\n",e)
                continue
            }
            countLines(f,counts,fileNames)
            f.Close()
        }
    }

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


func countLines(f *os.File,counts map[string]int,filenames map[string][]string){
    input := bufio.NewScanner(f)
    for input.Scan(){
        line := input.Text()
        counts[line]++
        if !contains(filenames[line],f.Name()){
            filenames[line] = append(filenames[line],f.Name())
        }
    }
}

func contains(names []string,target string) bool {
    for _,v := range names {
        if v == target {
            return true
        }
    }
    return false
}

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

// Lissajous generates GIF animations of random Lissajous figures
package main

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

var green = color.RGBA{0x00,0xff,0x00,0xff}

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

const(
    blackIndex = 0  //first color in palette
    greenIndex = 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 defference

    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),greenIndex)
        }
        phase += 0.1

        anim.Delay = append(anim.Delay,delay)
        anim.Image = append(anim.Image,img)
    }

    gif.EncodeAll(out,&anim) // NOTE: ignoring encoding errors
}

func main() {
    // The sequence of images if deterministic unless we seed
    // the pseudo-random number generator using the current time.
    rand.Seed(time.Now().UnixNano())

    if len(os.Args) > 1 && os.Args[1] == "web" {
        handler := func( w http.ResponseWriter,r *http.Request){
            lissajous(w)
        }
        http.HandleFunc("/",handler)
        log.Fatal(http.ListenAndServe("localhost:8000", nil))
        return
    }
    lissajous(os.Stdout)
}

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

// Lissajous generates GIF animations of random Lissajous figures
package main

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

var (
    red = color.RGBA{0xff,0x00,0x00,0xff}
    green = color.RGBA{0x00,0xff,0x00,0xff}
    blue = color.RGBA{0x00,0x00,0xff,0xff}
    cyan = color.RGBA{0x00,0xff,0xff,0xff}
    magenta = color.RGBA{0xff,0x00,0xff,0xff}
    yellow = color.RGBA{0xff,0xff,0x00,0xff}
)
var palette = []color.Color{color.Black, red, red, yellow, yellow, green, green, cyan, cyan, blue, blue, magenta, magenta}

const(
    blackIndex = 0  //first color in palette
    greenIndex = 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 defference

    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)
            colorIndex := uint8(i%(len(palette)-1)+1)
            img.SetColorIndex(size+int(x*size+0.5),size+int(y*size+0.5),colorIndex)
        }
        phase += 0.1

        anim.Delay = append(anim.Delay,delay)
        anim.Image = append(anim.Image,img)
    }

    gif.EncodeAll(out,&anim) // NOTE: ignoring encoding errors
}

func main() {
    // The sequence of images if deterministic unless we seed
    // the pseudo-random number generator using the current time.
    rand.Seed(time.Now().UnixNano())

    if len(os.Args) > 1 && os.Args[1] == "web" {
        handler := func( w http.ResponseWriter,r *http.Request){
            lissajous(w)
        }
        http.HandleFunc("/",handler)
        log.Fatal(http.ListenAndServe("localhost:8000", nil))
        return
    }
    lissajous(os.Stdout)
}

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

package main

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

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)
        }
        _, err = io.Copy(os.Stdout, resp.Body)
        resp.Body.Close()
        if err != nil {
            fmt.Fprintf(os.Stderr,"fetch: reading %s : %v ",url,err)
            os.Exit(1)
        }
    }
}

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

package main

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

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

    }
}

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

package main

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

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)
        }
        bytes, err := ioutil.ReadAll(resp.Body)//申请一个缓存区 bytes
        resp.Body.Close()
        if err != nil {
            fmt.Fprintf(os.Stderr,"fetch: reading %s: %v\n",url,err)
            os.Exit(1)
        }
        fmt.Printf("%s\n%s",resp.Status,bytes)
    }
}

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

//Fetchall fetches URLs in parallel and reports their times and sizes.
package main

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

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
    }

    filename := getFileName(url)
    file, err := os.Create(filename)
    if err != nil {
        ch <- fmt.Sprint(err)
        return
    }
    defer file.Close()


    nbytes, err := io.Copy(file, resp.Body)
    resp.Body.Close()
    if err != nil {
        ch <- fmt.Sprintf("while reading %s: %v",url,err)
        return
    }
    secs := time.Since(start).Seconds()
    ch <- fmt.Sprintf("%.2fs %7d %s \t-> %s",secs,nbytes,url,filename)
}

func getFileName(url string) string {
    basename := url
    index := strings.Index(basename,"://") + len("://")
    if index > 0 {
        basename = basename[index:len(basename)]
    }
    filename := basename
    for i := 1; i <= 10; i++ {
        if !exists(filename) {
            return filename
        }
        filename = basename + "." + strconv.Itoa(i)
    }
    return basename


}

func exists(filename string ) bool {
    _, err := os.Stat(filename)
    return err == nil
}

练习 1.11: 在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
    }
    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)
}

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

// Lissajous generates GIF animations of random Lissajous figures
package main

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

var (
    red = color.RGBA{0xff,0x00,0x00,0xff}
    green = color.RGBA{0x00,0xff,0x00,0xff}
    blue = color.RGBA{0x00,0x00,0xff,0xff}
    cyan = color.RGBA{0x00,0xff,0xff,0xff}
    magenta = color.RGBA{0xff,0x00,0xff,0xff}
    yellow = color.RGBA{0xff,0xff,0x00,0xff}
)
var palette = []color.Color{color.Black, red, red, yellow, yellow, green, green, cyan, cyan, blue, blue, magenta, magenta}

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

)
var (
    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
)

func lissajous(out io.Writer){
    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 < float64(cycles)*2*math.Pi; t += res {
            x := math.Sin(t)
            y := math.Sin(t*freq + phase)
            colorIndex := uint8(i%(len(palette)-1)+1)
            img.SetColorIndex(size+int(x*float64(size)+0.5),size+int(y*float64(size)+0.5),colorIndex)
        }
        phase += 0.1

        anim.Delay = append(anim.Delay,delay)
        anim.Image = append(anim.Image,img)
    }

    gif.EncodeAll(out,&anim) // NOTE: ignoring encoding errors
}

func main() {
    // The sequence of images if deterministic unless we seed
    // the pseudo-random number generator using the current time.
    rand.Seed(time.Now().UnixNano())

    if len(os.Args) > 1 && os.Args[1] == "web" {
        handler := func( w http.ResponseWriter,r *http.Request){
            if err := r.ParseForm(); err != nil {
                log.Print(err)
            }
            for k,v := range r.Form {
                switch k {
                case "cycles":
                    cycles,_ = strconv.Atoi(v[0])
                case "res":
                    res,_ = strconv.ParseFloat(v[0],64)
                case "size":
                    size,_ = strconv.Atoi(v[0])
                case "nframes":
                    nframes,_ = strconv.Atoi(v[0])
                case "delay":
                    delay,_= strconv.Atoi(v[0])

                }
            }
            lissajous(w)
        }
        http.HandleFunc("/",handler)
        log.Fatal(http.ListenAndServe("localhost:8000", nil))
        return
    }
    lissajous(os.Stdout)
}


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
禁止转载,如需转载请通过简信或评论联系作者。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,165评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,720评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,849评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,245评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,596评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,747评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,977评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,708评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,448评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,657评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,141评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,493评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,153评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,890评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,799评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,685评论 2 272

推荐阅读更多精彩内容