semester.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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, "weeks/") {
  21. GetSemestersByWeeks(w, r, num)
  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, num int) {
  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. return
  47. }
  48. var semesters []Semester
  49. settings.DB.Where("weeksquantity = ?", num).Find(&semesters)
  50. json.NewEncoder(w).Encode(semesters)
  51. return
  52. }
  53. func GetSemesterById(w http.ResponseWriter, r *http.Request, num int) {
  54. var Semester Semester
  55. settings.DB.Where("id = ?", num).First(&Semester)
  56. json.NewEncoder(w).Encode(Semester)
  57. return
  58. }
  59. func GetSemesters(w http.ResponseWriter, r *http.Request) {
  60. showAPIRequest(r)
  61. w.Header().Set("Content-Type", "application/json")
  62. if r.Method == "GET" {
  63. var Semesters []Semester
  64. settings.DB.Find(&Semesters)
  65. json.NewEncoder(w).Encode(Semesters)
  66. }
  67. return
  68. }