• Go语言*习题练习_1.7. Web服务


    练习 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
    ", r.Method, r.URL, r.Proto)
    	fmt.Fprintf(w, "URL.Path = %q
    ", 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))
    }
    

      

  • 相关阅读:
    黑盒测试用例输入:等价类划分方法
    jar包/class文件如何快速反编译成java文件
    html表格单元格添加斜下框线的方法
    Linux常用命令操作文档
    压力、负载、性能测试工具总结(持续更新。。。)
    压力测试、负载测试及性能测试异同
    Mac os x安装IDEAL及配置JDK和Maven
    RMQ问题总结,标准RMQ算法的实现
    [c++ IO加速]快速输入输出
    [coj 1353 Guessing the Number]kmp,字符串最小表示法
  • 原文地址:https://www.cnblogs.com/yzhch/p/6376794.html
Copyright © 2020-2023  润新知