-
Notifications
You must be signed in to change notification settings - Fork 4
/
plotly08.go
75 lines (66 loc) · 1.8 KB
/
plotly08.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Seriál "Programovací jazyk Go"
// https://www.root.cz/serialy/programovaci-jazyk-go/
//
// Padesátá první část
// Tvorba grafů v jazyce Go: kreslení ve webovém klientu
// https://www.root.cz/clanky/tvorba-grafu-v-jazyce-go-kresleni-ve-webovem-klientu/
//
// Repositář:
// https://github.com/tisnik/go-root/
//
// Seznam demonstračních příkladů z padesáté první části:
// https://github.com/tisnik/go-root/blob/master/article_51/README.md
package main
import (
"encoding/json"
"log"
"math"
"net/http"
"strconv"
)
type Points struct {
X []float64 `json:"x"`
Y []float64 `json:"y"`
}
const npoints = 100
const periods = 2
func makePoints(npoints uint, offset float64) Points {
var points Points
points.X = make([]float64, npoints)
points.Y = make([]float64, npoints)
for i := uint(0); i < npoints; i++ {
t := float64(i) * periods * 2.0 * math.Pi / float64(npoints)
points.X[i] = t
// limita
if t == 0.0 {
points.Y[i] = 1.0
} else {
points.Y[i] = math.Sin(t+offset) / t
}
}
return points
}
func writePoints(writer http.ResponseWriter, points Points) {
writer.Header().Set("Content-Type", "application/json")
writer.WriteHeader(http.StatusOK)
json.NewEncoder(writer).Encode(points)
}
func seriesHandler(writer http.ResponseWriter, request *http.Request) {
offsetStr := request.URL.Query().Get("offset")
offset, err := strconv.ParseFloat(offsetStr, 64)
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
return
}
points := makePoints(npoints, offset)
writePoints(writer, points)
}
func startHttpServer(address string) {
log.Printf("Starting server on address %s", address)
http.Handle("/", http.FileServer(http.Dir("plotly08/")))
http.HandleFunc("/series", seriesHandler)
http.ListenAndServe(address, nil)
}
func main() {
startHttpServer(":8080")
}