练习1.12
描述:修改Lissajour服务,从URL读取变量,比如你可以访问 http://localhost:8000/?cycles=20 这个URL,这样访问可以将程序里的cycles默认的5修改为20。字符串转换为数字可以调用strconv.Atoi函数。你可以在godoc里查看strconv.Atoi的详细说明。
代码:
package main
import (
"fmt"
"image"
"image/color"
"image/gif"
"io"
"log"
"math"
"math/rand"
"net/http"
"strconv"
"sync"
)
var green = color.RGBA{0x00, 0xFF, 0x00, 0xFF} //生成绿色
var red = color.RGBA{0xFF, 0x00, 0x00, 0xFF}
var blue = color.RGBA{0x00, 0x00, 0xFF, 0xFF}
var palette = []color.Color{color.White, green, red, blue} //生成一个slice切片
var mu sync.Mutex
var count int
func main() {
http.HandleFunc("/", handler)
//http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// lissajous(w, r)
//})
//http.HandleFunc("/count", counter)
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
func handler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
lissajous(w, r)
} else {
http.NotFound(w, r)
}
}
func lissajous(out io.Writer, r *http.Request) {
query := r.URL.Query()
cyclesStr := query.Get("cycles")
cyclevalue, err := strconv.Atoi(cyclesStr)
if err != nil {
// If conversion fails, log the error and return
fmt.Println("Invalid 'cycles' parameter: %v", err)
return
}
var cycles = float64(cyclevalue)
const (
// 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} //struct结构体
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),
2)
}
phase += 0.1
anim.Delay = append(anim.Delay, delay)
anim.Image = append(anim.Image, img)
}
gif.EncodeAll(out, &anim) // NOTE: ignoring encoding errors
}
运行:
PS:
这里,我先通过handler对函数lissajous做了一层封装,这样可以避免浏览器会自动发起一个额外的请求,通常是请求网站的图标(favicon.ico)。可以在你的lissajous中打印cyclevalue,你会发现发起请求时候,打印出了一个2和一个0。但通过上述handler封装可以避免该问题。