server.go 2.1 KB

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