bellschedule.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package api
  2. import (
  3. "../settings"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "strconv"
  8. // "strings"
  9. )
  10. var Lessons []Lesson
  11. func BellScheduleRoute(w http.ResponseWriter, r *http.Request) {
  12. showAPIRequest(r)
  13. w.Header().Set("Content-Type", "application/json")
  14. if r.Method == "POST" {
  15. CreateLesson(w, r)
  16. return
  17. }
  18. if r.Method == "UPDATE" || r.Method == "PATCH" {
  19. UpdateLesson(w, r)
  20. return
  21. }
  22. path := replacePath(r.URL.Path, "/api/bellschedule/")
  23. if path == "" {
  24. GetLessons(w, r)
  25. return
  26. }
  27. num, err := strconv.Atoi(path)
  28. if err != nil {
  29. json.NewEncoder(w).Encode(struct{ Error string }{Error: "strconv error"})
  30. fmt.Println(err)
  31. return
  32. }
  33. settings.DB.Find(&Lessons)
  34. if num < 0 || num > len(Lessons)+1 {
  35. json.NewEncoder(w).Encode(struct{ Error string }{Error: "strconv error"})
  36. fmt.Println(err)
  37. return
  38. }
  39. if r.Method == "GET" {
  40. //db.Where("name = ?", "jinzhu").First(&user)
  41. GetLessonById(w, r, num)
  42. return
  43. }
  44. json.NewEncoder(w).Encode(struct{ Error string }{Error: "This method is not supported"})
  45. }
  46. func UpdateLesson(w http.ResponseWriter, r *http.Request) {
  47. var lesson Lesson
  48. var LessonToUpdate Lesson
  49. err := json.NewDecoder(r.Body).Decode(&lesson)
  50. if err != nil {
  51. showError(r, err)
  52. json.NewEncoder(w).Encode(struct{ Error string }{Error: "error update Lesson"})
  53. return
  54. }
  55. settings.DB.First(&LessonToUpdate, lesson.ID)
  56. settings.DB.Model(&LessonToUpdate).Updates(lesson)
  57. json.NewEncoder(w).Encode(struct{ Result string }{Result: "updated Lesson"})
  58. return
  59. }
  60. func CreateLesson(w http.ResponseWriter, r *http.Request) {
  61. var newLesson Lesson
  62. err := json.NewDecoder(r.Body).Decode(&newLesson)
  63. if err != nil {
  64. json.NewEncoder(w).Encode(struct{ Error string }{Error: "error add new Lesson"})
  65. fmt.Println(err)
  66. return
  67. }
  68. settings.DB.Create(&newLesson)
  69. json.NewEncoder(w).Encode(struct{ Result string }{Result: "added new Lesson"})
  70. return
  71. }
  72. func GetLessonById(w http.ResponseWriter, r *http.Request, num int) {
  73. var Lesson Lesson
  74. settings.DB.Where("id = ?", num).First(&Lesson)
  75. json.NewEncoder(w).Encode(Lesson)
  76. return
  77. }
  78. func GetLessons(w http.ResponseWriter, r *http.Request) {
  79. showAPIRequest(r)
  80. w.Header().Set("Content-Type", "application/json")
  81. if r.Method == "GET" {
  82. var Lessons1 []Lesson
  83. settings.DB.Find(&Lessons1)
  84. json.NewEncoder(w).Encode(Lessons1)
  85. }
  86. return
  87. }