forked from mtlynch/hello-world-cypress
-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathmain.go
107 lines (98 loc) · 2.56 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"os"
"unicode"
)
type PageVariables struct {
Sentiment string
}
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
log.Printf("Listening on port %s", port)
http.HandleFunc("/", AnalyzePage)
http.HandleFunc("/analyze", AnalyzePage)
http.HandleFunc("/results", ResultsPage)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}
func AnalyzePage(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(w, `
<!DOCTYPE html>
<html>
<head>
<title>Sentimentalyzer</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container">
<p>Welcome to Sentimentalyzer, the world's simplest sentiment analyzer!</p>
<form action="/results" method="post">
<div class="form-group">
<label for="feelings">How are you feeling?</label>
<textarea class="form-control" rows="5" name="feelings" id="feelings"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>
`)
}
func ResultsPage(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
ResultsPageVars := PageVariables{
Sentiment: detectSentiment(r.Form.Get("feelings")),
}
err = template.Must(template.New("T").Parse(`
<!DOCTYPE html>
<html>
<head>
<title>Sentimentalyzer</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="results container">
<h1>Results</h1>
<p>You are feeling: <b>{{.Sentiment}}</b></p>
</div>
</body>
</html>
`)).Execute(w, ResultsPageVars)
if err != nil {
log.Print("Error generating page: ", err)
}
}
func detectSentiment(feelings string) string {
cu := countUpperCaseCharacters(feelings)
cTot := countLetters(feelings)
if float64(cu)/float64(cTot) > 0.5 {
return "Angry"
} else {
return "Content"
}
}
func countUpperCaseCharacters(str string) int {
count := 0
for _, c := range str {
if unicode.IsUpper(c) {
count++
}
}
return count
}
func countLetters(str string) int {
count := 0
for _, c := range str {
if unicode.IsLetter(c) {
count++
}
}
return count
}