zoukankan      html  css  js  c++  java
  • 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))
    }
    

      

  • 相关阅读:
    使用特殊构造的5GB文件测试Win2012Dedup功能
    VMWare 回收磁盘空间
    一个极其高效的虚拟机内存冗余消除机制:UKSM
    基于Dedup的数据打包技术
    hadoop集群运行dedup实现去重功能
    Qt编写安防视频监控系统24-自定义悬浮条
    Qt编写百度地图综合应用(在线+离线+区域)
    Qt编写安防视频监控系统23-图片地图
    Qt编写安防视频监控系统22-摄像机搜索
    Qt编写安防视频监控系统21-摄像机管理
  • 原文地址:https://www.cnblogs.com/yzhch/p/6376794.html
Copyright © 2011-2022 走看看