-
Notifications
You must be signed in to change notification settings - Fork 15
/
main.go
70 lines (57 loc) · 1.78 KB
/
main.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
package main
import (
"fmt"
"log"
"math"
"net/http"
"github.com/VividCortex/siesta"
)
func main() {
// Create a new Service rooted at "/"
service := siesta.NewService("/")
// Here's a handler that uses a URL parameter.
// Example: GET /greet/Bob
service.Route("GET", "/greet/:name", "Greets with a name.",
func(w http.ResponseWriter, r *http.Request) {
var params siesta.Params
name := params.String("name", "", "Person's name")
err := params.Parse(r.Form)
if err != nil {
log.Println("Error parsing parameters!", err)
return
}
fmt.Fprintf(w, "Hello, %s!", *name)
},
)
// Here's a handler that uses a query string parameter.
// Example: GET /square?number=10
service.Route("GET", "/square", "Prints the square of a number.",
func(w http.ResponseWriter, r *http.Request) {
var params siesta.Params
number := params.Int("number", 0, "A number to square")
err := params.Parse(r.Form)
if err != nil {
log.Println("Error parsing parameters!", err)
return
}
fmt.Fprintf(w, "%d * %d = %d.", *number, *number, (*number)*(*number))
},
)
// We can also use both URL and query string parameters.
// Example: GET /exponentiate/10?power=10
service.Route("GET", "/exponentiate/:number", "Exponentiates a number.",
func(w http.ResponseWriter, r *http.Request) {
var params siesta.Params
number := params.Float64("number", 0, "A number to exponentiate")
power := params.Float64("power", 1, "Power")
err := params.Parse(r.Form)
if err != nil {
log.Println("Error parsing parameters!", err)
return
}
fmt.Fprintf(w, "%g ^ %g = %g.", *number, *power, math.Pow(*number, *power))
},
)
// service is an http.Handler, so we can pass it directly to ListenAndServe.
log.Fatal(http.ListenAndServe(":8080", service))
}