server.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package main
  2. import (
  3. "flag"
  4. "html/template"
  5. "log"
  6. "net/http"
  7. "time"
  8. )
  9. var host = flag.String("h", "localhost", "host")
  10. var port = flag.String("p", "80", "port")
  11. var url = flag.String("b", "", "API URL")
  12. var app Application
  13. var errorPage = template.Must(template.ParseFiles("./html/error.html"))
  14. func serveIndex(w http.ResponseWriter, r *http.Request) {
  15. t := template.Must(template.ParseFiles("./html/index.html"))
  16. t.Execute(w, app.Languages)
  17. }
  18. func displaySearchResults(w http.ResponseWriter, r *http.Request) {
  19. var info SearchInfo
  20. info.GetInfoFromRequest(r)
  21. if info.Phrase == "" {
  22. errorPage.Execute(w, "You need to enter search phrase!")
  23. return
  24. }
  25. if info.LanguageCode != "" && !app.checkLanguage(info.LanguageCode) {
  26. errorPage.Execute(w, "Language not valid!")
  27. return
  28. }
  29. searchResults := app.search(app.GetTMs(info.LanguageCode), info.Phrase)
  30. info.ResultsServed = searchResults.TotalResults
  31. writeLog(info)
  32. if len(searchResults.Results) == 0 {
  33. errorPage.Execute(w, "Nothing found!")
  34. return
  35. }
  36. t := template.Must(template.New("results.html").ParseFiles("./html/results.html"))
  37. t.Execute(w, searchResults)
  38. }
  39. func displayTMs(w http.ResponseWriter, r *http.Request) {
  40. var info SearchInfo
  41. info.GetInfoFromRequest(r)
  42. if info.LanguageCode != "" && !app.checkLanguage(info.LanguageCode) {
  43. errorPage.Execute(w, "Language not valid!")
  44. return
  45. }
  46. TMList := app.GetTMs(info.LanguageCode)
  47. info.ResultsServed = len(TMList)
  48. writeLog(info)
  49. if info.ResultsServed == 0 {
  50. errorPage.Execute(w, "No TMs to display!")
  51. return
  52. }
  53. t := template.Must(template.New("tms.html").ParseFiles("./html/tms.html"))
  54. t.Execute(w, TMList)
  55. }
  56. func main() {
  57. flag.Parse()
  58. if *url == "" {
  59. log.Fatalln("Can't do anything without URL to API")
  60. }
  61. app.setBaseURL(*url)
  62. status, err := app.login()
  63. if !status || err != nil {
  64. log.Fatalf("Couldn't log in: %s", err)
  65. }
  66. app.loadLanguages()
  67. app.Delay = time.Duration(20 * time.Second)
  68. hostname := *host + ":" + *port
  69. http.HandleFunc("/", serveIndex)
  70. http.HandleFunc("/q", displaySearchResults)
  71. http.HandleFunc("/tms", displayTMs)
  72. http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
  73. log.Fatal(http.ListenAndServe(hostname, nil))
  74. }