• 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))
    }
    

      

  • 相关阅读:
    超好用的Redis管理及监控工具,使用后可大大提高你的工作效率!
    MySQL,Oracle,PostgreSQL,DB2,mongoDB,Hive, SAP HANA 数据库web维护客户端管理工具
    DB2定时循环同步数据到MySQL
    SQL Server数据同步到MySQL
    powerDesign导出word操作步骤
    数据库工单的主要业务流程
    Redshift数据库客户端工具的使用
    如何提高数据库管理质量?
    远程管理mysql数据库
    SQL工单管理
  • 原文地址:https://www.cnblogs.com/yzhch/p/6376794.html
Copyright © 2020-2023  润新知