semester.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package api
  2. import (
  3. "../settings"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. )
  10. var Semesters []Semester
  11. func SemesterRoute(w http.ResponseWriter, r *http.Request) {
  12. showAPIRequest(r)
  13. w.Header().Set("Content-Type", "application/json")
  14. path := replacePath(r.URL.Path, "/api/semester/")
  15. num, err := strconv.Atoi(path)
  16. if path == "" {
  17. GetSemesters(w, r)
  18. return
  19. }
  20. if strings.Contains(path, "day/") {
  21. GetSemestersByWeeks(w, r)
  22. return
  23. }
  24. if err != nil {
  25. json.NewEncoder(w).Encode(struct{ Error string }{Error: "strconv error"})
  26. fmt.Println(err)
  27. return
  28. }
  29. settings.DB.Find(&Semesters)
  30. if num < 0 || num > len(Semesters)+1 {
  31. json.NewEncoder(w).Encode(struct{ Error string }{Error: "strconv error"})
  32. fmt.Println(err)
  33. return
  34. }
  35. if r.Method == "GET" {
  36. GetSemesterById(w, r, num)
  37. return
  38. }
  39. json.NewEncoder(w).Encode(struct{ Error string }{Error: "This method is not supported"})
  40. }
  41. func GetSemestersByWeeks(w http.ResponseWriter, r *http.Request) {
  42. path := replacePath(r.URL.Path, "/api/semester/weeks/")
  43. num, err := strconv.Atoi(path)
  44. if err != nil || num < 0 {
  45. json.NewEncoder(w).Encode(struct{ Error string }{Error: "strconv error"})
  46. }
  47. var semesters []Semester
  48. settings.DB.Where("weeksquantity = ?", num).Find(&semesters)
  49. json.NewEncoder(w).Encode(semesters)
  50. return
  51. }
  52. func GetSemesterById(w http.ResponseWriter, r *http.Request, num int) {
  53. var Semester Semester
  54. settings.DB.Where("id = ?", num).First(&Semester)
  55. json.NewEncoder(w).Encode(Semester)
  56. return
  57. }
  58. func GetSemesters(w http.ResponseWriter, r *http.Request) {
  59. showAPIRequest(r)
  60. w.Header().Set("Content-Type", "application/json")
  61. if r.Method == "GET" {
  62. var Semesters []Semester
  63. settings.DB.Find(&Semesters)
  64. json.NewEncoder(w).Encode(Semesters)
  65. }
  66. return
  67. }