85 lines
2.2 KiB
Go
85 lines
2.2 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"io/ioutil"
|
|
"os"
|
|
"encoding/json"
|
|
"log"
|
|
"net/http"
|
|
"math/rand"
|
|
"strconv"
|
|
)
|
|
type Phrase struct {
|
|
Phrase string `json:"phrase"`
|
|
Mode bool `json:"mode"`
|
|
Answer string `json:"answer"`
|
|
}
|
|
type Phrases struct {
|
|
Phrases []Phrase `json:"phrases"`
|
|
}
|
|
var phrases Phrases
|
|
func ParseJSON() {
|
|
jsonFile, err := os.Open("phrases.json")
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
defer jsonFile.Close()
|
|
byteValue, _ := ioutil.ReadAll(jsonFile)
|
|
err = json.Unmarshal(byteValue, &phrases)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
}
|
|
func requestHandler(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "text/html")
|
|
i := rand.Intn(len(phrases.Phrases))
|
|
fmt.Fprintf(w, `
|
|
<meta charset="UTF-8"><html><body>%s
|
|
<form action="/answer/%d" method="POST">
|
|
<input type="text" autocomplete="off" name="answer" />
|
|
<input type="submit" value="verifique" />
|
|
</form>
|
|
</body></html>
|
|
`, phrases.Phrases[i].Phrase, i)
|
|
}
|
|
func answerHandler(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "text/html")
|
|
i, err := strconv.Atoi(r.URL.Path[len("/answer/"):])
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
p := phrases.Phrases[i]
|
|
pageContent := "<meta charset=\"UTF-8\"><html><body><b>" + p.Phrase + "</b><br /"
|
|
if p.Mode == true {
|
|
pageContent += "<i>aquí nececitamos el subjuntivo:</i><br />"
|
|
} else {
|
|
pageContent += "<i>aquí nececitamos el indicativo:</i><br />"
|
|
}
|
|
pageContent += p.Answer + "<br /> tu respuesta estaba "
|
|
if r.FormValue("answer") == p.Answer {
|
|
pageContent += "<b>correcta!</b>. Buen hecho<br /"
|
|
} else {
|
|
pageContent += "<b>falsa :'-(</b><br />"
|
|
}
|
|
j := rand.Intn(len(phrases.Phrases)-1)
|
|
if j>=i {
|
|
j++
|
|
}
|
|
pageContent+= "<br />frase nueva: " + phrases.Phrases[j].Phrase + `<br />
|
|
<form action="/answer/`+ strconv.Itoa(j) +`" method="POST">
|
|
<input type="text" autocomplete="off" name="answer" />
|
|
<input type="submit" value="verifique" />
|
|
</form>`
|
|
pageContent += "</body></html>"
|
|
fmt.Fprintf(w,pageContent)
|
|
}
|
|
func main() {
|
|
ParseJSON()
|
|
/* for _, phrase := range phrases.Phrases {
|
|
fmt.Println(phrase.Phrase)
|
|
}*/
|
|
http.HandleFunc("/", requestHandler)
|
|
http.HandleFunc("/answer/", answerHandler)
|
|
log.Fatal(http.ListenAndServe(":8080", nil))
|
|
}
|