-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
77 lines (57 loc) · 1.6 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
71
72
73
74
75
76
77
package main
import (
"fmt"
"html/template"
"net/http"
"os"
"strconv"
"github.com/satriaa14/test-driven-deployment/models"
)
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "3031"
}
svr := ":" + port
http.HandleFunc("/", routeIndexGet)
http.HandleFunc("/hasil", routeSubmitPost)
fmt.Printf("server started at localhost%s", svr)
http.ListenAndServe(svr, nil)
}
func routeIndexGet(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
var tmpl = template.Must(template.New("form").ParseFiles("./src/index.html"))
var err = tmpl.Execute(w, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
http.Error(w, "", http.StatusBadRequest)
}
func routeSubmitPost(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
var tmpl = template.Must(template.New("result").ParseFiles("./src/index.html"))
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var num1 = r.Form.Get("num1")
num1Conv, _ := strconv.ParseFloat(num1, 64)
var num2 = r.Form.Get("num2")
num2Conv, _ := strconv.ParseFloat(num2, 64)
var tipe = r.Form.Get("tipe")
var nilai = models.Nilai{A: num1Conv, B: num2Conv, Tipe: tipe}
result, _ := nilai.Perhitungan()
resultStr := fmt.Sprintf("%f", result)
var data = map[string]string{"num1": num1,
"num2": num2,
"tipe": tipe,
"result": resultStr}
if err := tmpl.Execute(w, data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
http.Error(w, "", http.StatusBadRequest)
}