server.go 2.3 KB

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