首页 > 技术文章 > Go语言圣经习题练习_1.7. Web服务

yzhch 2017-02-08 09:50 原文

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

package main

import (
	"fmt"
	"log"
	"net/http"
	"image/gif"
	"image"
	"math"
	"math/rand"
	"io"
	"image/color"
	"strconv"
)
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, myCycles float64) { //接收 cycles参数
	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
	)
	if myCycles == 0 {
		myCycles = cycles //如果为零,则使用常亮定义的值
	}
	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 < myCycles*2*math.Pi; t += res { //使用myCycles变量
			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
}

func handler(w http.ResponseWriter, r *http.Request)  {
	fmt.Fprintf(w, "%s %s %s\n", r.Method, r.URL, r.Proto)
	fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
}

func handler_gif(w http.ResponseWriter,r *http.Request) {
	if err := r.ParseForm(); err != nil {
		log.Print(err)
	}
	if r.Form["cycles"] != nil { // 获取cycles参数,并转为int型
		cycles,err := strconv.Atoi(r.Form["cycles"][0]) 
		if err != nil {
			lissajous(w,float64(cycles)) 
		}
	}
	lissajous(w,float64(0))
}
func main() {
	http.HandleFunc("/", handler) // each request calls handler
	http.HandleFunc("/gif", handler_gif) // each request calls handler
	log.Println("localhost:8000")
	log.Fatal(http.ListenAndServe("localhost:8000", nil))
}

  

 

推荐阅读