attestation.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package api
  2. import (
  3. "../settings"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "strconv"
  8. // "strings"
  9. )
  10. var attestations []Attestation
  11. func AttestationRoute(w http.ResponseWriter, r *http.Request) {
  12. showAPIRequest(r)
  13. w.Header().Set("Content-Type", "application/json")
  14. if r.Method == "UPDATE" || r.Method == "PATCH" {
  15. UpdateAttestation(w, r)
  16. return
  17. }
  18. path := replacePath(r.URL.Path, "/api/attestation/")
  19. if path == "" {
  20. GetAttestations(w, r)
  21. return
  22. }
  23. num, err := strconv.Atoi(path)
  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(&attestations)
  30. if num < 0 || num > len(attestations)+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. GetAttestationById(w, r, num)
  37. return
  38. }
  39. json.NewEncoder(w).Encode(struct{ Error string }{Error: "This method is not supported"})
  40. }
  41. func UpdateAttestation(w http.ResponseWriter, r *http.Request) {
  42. var attestation Attestation
  43. var AttestationToUpdate Attestation
  44. err := json.NewDecoder(r.Body).Decode(&attestation)
  45. if err != nil {
  46. showError(r, err)
  47. json.NewEncoder(w).Encode(struct{ Error string }{Error: "error update Attestation"})
  48. return
  49. }
  50. settings.DB.First(&AttestationToUpdate, attestation.ID)
  51. settings.DB.Model(&AttestationToUpdate).Updates(attestation)
  52. json.NewEncoder(w).Encode(struct{ Result string }{Result: "updated Attestation"})
  53. return
  54. }
  55. func GetAttestationById(w http.ResponseWriter, r *http.Request, num int) {
  56. var Attestation Attestation
  57. settings.DB.Where("id = ?", num).First(&Attestation)
  58. json.NewEncoder(w).Encode(Attestation)
  59. return
  60. }
  61. func GetAttestations(w http.ResponseWriter, r *http.Request) {
  62. showAPIRequest(r)
  63. w.Header().Set("Content-Type", "application/json")
  64. if r.Method == "GET" {
  65. var Attestations []Attestation
  66. settings.DB.Find(&Attestations)
  67. json.NewEncoder(w).Encode(Attestations)
  68. }
  69. return
  70. }