server.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. // ServeIndex serves index page.
  15. func serveIndex(w http.ResponseWriter, r *http.Request) {
  16. t := template.Must(template.ParseFiles("./html/index.html"))
  17. t.Execute(w, app.Languages)
  18. }
  19. // DisplaySearchResults displays search results as HTML page.
  20. func displaySearchResults(w http.ResponseWriter, r *http.Request) {
  21. var info SearchInfo
  22. info.GetInfoFromRequest(r)
  23. if info.Phrase != "" {
  24. var searchResults SearchResults
  25. if info.LanguageCode == "" || app.CheckLanguage(info.LanguageCode) {
  26. searchResults = app.Search(app.GetTMs(info.LanguageCode), info.Phrase)
  27. info.ResultsServed = searchResults.TotalResults
  28. WriteLog(info)
  29. } else {
  30. errorPage.Execute(w, "Language not valid!")
  31. return
  32. }
  33. if len(searchResults.Results) > 0 {
  34. t := template.Must(template.New("results.html").ParseFiles("./html/results.html"))
  35. t.Execute(w, searchResults)
  36. } else {
  37. errorPage.Execute(w, "Nothing found!")
  38. }
  39. } else {
  40. errorPage.Execute(w, "You need to enter search phrase!")
  41. }
  42. }
  43. // DisplayTMs displays TMs as HTML page.
  44. func displayTMs(w http.ResponseWriter, r *http.Request) {
  45. var info SearchInfo
  46. info.GetInfoFromRequest(r)
  47. var TMList []TM
  48. if info.LanguageCode == "" || app.CheckLanguage(info.LanguageCode) {
  49. TMList = app.GetTMs(info.LanguageCode)
  50. info.ResultsServed = len(TMList)
  51. WriteLog(info)
  52. } else {
  53. errorPage.Execute(w, "Language not valid!")
  54. return
  55. }
  56. if len(TMList) > 0 {
  57. t := template.Must(template.New("tms.html").ParseFiles("./html/tms.html"))
  58. t.Execute(w, TMList)
  59. } else {
  60. errorPage.Execute(w, "No TMs to display!")
  61. }
  62. }
  63. func main() {
  64. flag.Parse()
  65. app.SetBaseURL(*url)
  66. if app.BaseURL == "" {
  67. log.Fatalln("Can't do anything without URL to API")
  68. }
  69. app.Login()
  70. app.LoadLanguages()
  71. app.Delay = time.Duration(20 * time.Second)
  72. hostname := *host + ":" + *port
  73. http.HandleFunc("/", serveIndex)
  74. http.HandleFunc("/q", displaySearchResults)
  75. http.HandleFunc("/tms", displayTMs)
  76. http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
  77. log.Fatal(http.ListenAndServe(hostname, nil))
  78. }