-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path09_factorial_compute.go
More file actions
76 lines (67 loc) · 1.8 KB
/
09_factorial_compute.go
File metadata and controls
76 lines (67 loc) · 1.8 KB
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
// Seriál "Programovací jazyk Go"
// https://www.root.cz/serialy/programovaci-jazyk-go/
//
// Dvanáctá část
// Vývoj síťových aplikací v programovacím jazyku Go (pokračování)
// https://www.root.cz/clanky/vyvoj-sitovych-aplikaci-v-programovacim-jazyku-go-pokracovani/
//
// Repositář:
// https://github.com/tisnik/go-root/
//
// Seznam demonstračních příkladů z dvanácté části:
// https://github.com/tisnik/go-root/blob/master/article_12/README.md
//
// Demonstrační příklad číslo 9:
// Druhá varianta webové aplikace pro výpočet faktoriálu
//
// Dokumentace ve stylu "literate programming":
// https://tisnik.github.io/go-root/article_12/09_factorial_compute.html
package main
import (
"fmt"
"html/template"
"net/http"
"strconv"
)
// FactorialPageDynContent holds all required information for factorial page template
type FactorialPageDynContent struct {
N int64
Result int64
}
// Factorial computes factorial for a given n that must be non negative integer
func Factorial(n int64) int64 {
switch {
case n < 0:
return 1
case n == 0:
return 1
default:
return n * Factorial(n-1)
}
}
func mainEndpoint(writer http.ResponseWriter, request *http.Request) {
err := request.ParseForm()
if err != nil {
writer.WriteHeader(http.StatusBadRequest)
return
}
n, err := strconv.ParseInt(request.FormValue("n"), 10, 64)
if err != nil {
n = 0
}
t, err := template.ParseFiles("factorial_compute.html")
if err != nil {
writer.WriteHeader(http.StatusNotFound)
fmt.Fprint(writer, "Not found!")
return
}
dynData := FactorialPageDynContent{N: n, Result: Factorial(n)}
err = t.Execute(writer, dynData)
if err != nil {
println("Error executing template")
}
}
func main() {
http.HandleFunc("/", mainEndpoint)
http.ListenAndServe(":8000", nil)
}