server.go 2.4 KB

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