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

  

最新文章

  1. Android源码——应用程序的消息处理机制
  2. 【HTML5】HTML5本地数据库(Web Sql Database)
  3. duilib进阶教程 -- 总结 (17)
  4. Uedit的快捷键
  5. plsql 简单介绍
  6. [bootstrap] 栅格系统和布局
  7. LinuxCmd
  8. python_virtualenvwrapper安装与使用
  9. git push提交报错,提示文件过大,且去掉大文件也报同样的错误
  10. [源码分析]StringBuffer
  11. 使用getInstance()方法的原因及作用
  12. nova client和nova restfull api区别
  13. 剑指offer(21)栈的压入、弹出序列
  14. SpringBoot之依赖注入DI
  15. thinkphp装修平台源码
  16. can总线实现stm32的IAP
  17. 1、数据库与excel表格的数据导入导出
  18. python 项目自动生成 requirements.txt 文件
  19. 《我是一只it小小鸟》观后感
  20. App简介及登录页面

热门文章

  1. 开源|性能优化利器:数据库审核平台Themis的选型与实践
  2. 安装metasploitable3的经验总结
  3. Flink UDF
  4. Java学习笔记——三层架构
  5. 【前端优化】js图片懒加载及优化
  6. Jenkins+GitLab+Docker+SpringCloud+Kubernetes实现可持续自动化微服务
  7. navicat远程连接mysql10060
  8. 分布式事务(1)---2PC和3PC理论
  9. django基础知识之模板:
  10. 如何让使用create-react-app构建的项目在build过程中如何不生成.map文件