利用Go语言实现一个简单的Web服务器,并在页面展示利萨茹(lissajous)图形。
server_lissajous.go
package main
import (
"fmt"
"image"
"image/color"
"image/gif"
"io"
"log"
"math"
"math/rand"
"net/http"
"sync"
)
var palette = []color.Color{color.White, color.Black}
const (
whiteIndex = 0 // first color in palette
blackIndex = 1 // next color in palette
)
var mu sync.Mutex
var count int
func main() {
hanlder := func(w http.ResponseWriter, r *http.Request) {
lissajous(w)
}
http.HandleFunc("/", hanlder) // 回声请求调用处理程序
// 回声请求调用处理程序
http.HandleFunc("/count", counter)
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
//counter回显目前为止调用的次数
func counter(w http.ResponseWriter, r *http.Request) {
mu.Lock()
fmt.Fprintf(w, "Count %d\n", count)
mu.Unlock()
}
//利萨茹图形实现函数
func lissajous(out io.Writer) {
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
)
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 < 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),
blackIndex)
}
phase += 0.1
anim.Delay = append(anim.Delay, delay)
anim.Image = append(anim.Image, img)
}
gif.EncodeAll(out, &anim) // NOTE: ignoring encoding errors
}
编写好上述代码过后,首先使用go build命令编译:
go build server_lissajous.go
正常情况下会在当前目录生成编译得到的二进制server_lissajous文件(如果编译没问题),然后使用go run命令启动服务即可:
go run server_lissajous.go &
这里我们使用过的端口为8000,如果提示端口已使用,请尝试kill掉占用端口的服务或者换一个从端口重试,上述的&表示不间断运行。
最后我们在浏览器输入:http://localhost:8000/
不出意外,我们将会看到如下: