server.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. tms := app.getTMs(info.LanguageCode)
  30. if len(tms) == 0 {
  31. errorPage.Execute(w, "Couldn't get TMs!")
  32. return
  33. }
  34. searchResults := app.search(tms, info.Phrase)
  35. info.ResultsServed = searchResults.TotalResults
  36. writeLog(info)
  37. if len(searchResults.Results) == 0 {
  38. errorPage.Execute(w, "Nothing found!")
  39. return
  40. }
  41. t := template.Must(template.New("results.html").ParseFiles("./html/results.html"))
  42. t.Execute(w, searchResults)
  43. }
  44. func displayTMs(w http.ResponseWriter, r *http.Request) {
  45. var info SearchInfo
  46. info.GetInfoFromRequest(r)
  47. if info.LanguageCode != "" && !app.checkLanguage(info.LanguageCode) {
  48. errorPage.Execute(w, "Language not valid!")
  49. return
  50. }
  51. TMList := app.getTMs(info.LanguageCode)
  52. info.ResultsServed = len(TMList)
  53. writeLog(info)
  54. if info.ResultsServed == 0 {
  55. errorPage.Execute(w, "No TMs to display!")
  56. return
  57. }
  58. t := template.Must(template.New("tms.html").ParseFiles("./html/tms.html"))
  59. t.Execute(w, TMList)
  60. }
  61. func main() {
  62. flag.Parse()
  63. if *url == "" {
  64. log.Fatalln("Can't do anything without URL to API")
  65. }
  66. app.setBaseURL(*url)
  67. status, err := app.login()
  68. if !status || err != nil {
  69. log.Fatalf("Couldn't log in: %s", err)
  70. }
  71. if !app.loadLanguages() {
  72. log.Fatal("Couldn't load languages!")
  73. }
  74. app.Delay = time.Duration(20 * time.Second)
  75. hostname := *host + ":" + *port
  76. http.HandleFunc("/", serveIndex)
  77. http.HandleFunc("/q", displaySearchResults)
  78. http.HandleFunc("/tms", displayTMs)
  79. http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
  80. log.Fatal(http.ListenAndServe(hostname, nil))
  81. }