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