-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexample.go
100 lines (85 loc) · 1.84 KB
/
example.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// +build ignore
package main
import (
"encoding/json"
"fmt"
"log"
"math"
"net/http"
)
// +extract
// FORMAT: 1A
//
// # Sums and Averages
//
// This API computes sums and averages (with standard deviation).
type jsonRequest struct {
Values []int `json:"values"`
}
// +extract
// ## POST /sum
// + Request (application/json)
//
// {
// "values": [ 10, 20, 30 ]
// }
//
// + Response 200 (application/json)
//
// {
// "sum": 60
// }
func sum(w http.ResponseWriter, r *http.Request) {
var j jsonRequest
dec := json.NewDecoder(r.Body)
if err := dec.Decode(&j); err != nil {
http.Error(w, "invalid json", http.StatusBadRequest)
return
}
var sum int
for _, v := range j.Values {
sum += v
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"sum": "%d"}`, sum)
}
// +extract
// ## POST /average
// + Request (application/json)
//
// {
// "values": [ 10, 20, 30 ]
// }
//
// + Response 200 (application/json)
//
// {
// "average": 20,
// "stddev": 10
// }
func average(w http.ResponseWriter, r *http.Request) {
var j jsonRequest
dec := json.NewDecoder(r.Body)
if err := dec.Decode(&j); err != nil {
http.Error(w, "invalid json", http.StatusBadRequest)
return
}
var sum, sqSum float64
for _, v := range j.Values {
sum += float64(v)
sqSum += float64(v * v)
}
var stddev float64
n := len(j.Values)
avg := float64(sum) / float64(n)
if n > 1 {
stddev = math.Sqrt((float64(n)*sqSum - sum*sum) / float64(n*(n-1)))
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"average": "%f", "stddev": "%f"}`, avg, stddev)
}
func main() {
http.Handle("/sum", http.HandlerFunc(sum))
http.Handle("/average", http.HandlerFunc(average))
log.Fatal(http.ListenAndServe(":9090", nil))
}