sshkey_handler.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package handlers
  2. import (
  3. "byom-infra-api/config"
  4. "encoding/json"
  5. "log"
  6. "net/http"
  7. "github.com/gorilla/mux"
  8. )
  9. type SSHKey struct {
  10. KeyName string `json:"keyName"`
  11. Key string `json:"key"`
  12. }
  13. type SSHKeyHandler struct{}
  14. func NewSSHKeyHandler() *SSHKeyHandler {
  15. return &SSHKeyHandler{}
  16. }
  17. // GetSSHKeys handles the retrieval of all SSH keys
  18. func (h *SSHKeyHandler) GetSSHKeys(w http.ResponseWriter, r *http.Request) {
  19. log.Printf("Handling GET request for all SSH keys from %s", r.RemoteAddr)
  20. // First, get the list of SSH key IDs
  21. var keyIDs []string
  22. err := config.OVHClient.Get("/me/sshKey", &keyIDs)
  23. if err != nil {
  24. log.Printf("Error fetching SSH key IDs: %v", err)
  25. http.Error(w, "Failed to fetch SSH keys: "+err.Error(), http.StatusInternalServerError)
  26. return
  27. }
  28. // Then fetch details for each key
  29. var sshKeys []SSHKey
  30. for _, id := range keyIDs {
  31. var key SSHKey
  32. err := config.OVHClient.Get("/me/sshKey/"+id, &key)
  33. if err != nil {
  34. log.Printf("Error fetching details for SSH key %s: %v", id, err)
  35. continue
  36. }
  37. sshKeys = append(sshKeys, key)
  38. }
  39. log.Printf("Successfully retrieved %d SSH keys", len(sshKeys))
  40. w.Header().Set("Content-Type", "application/json")
  41. if err := json.NewEncoder(w).Encode(sshKeys); err != nil {
  42. log.Printf("Error encoding SSH keys response: %v", err)
  43. http.Error(w, "Failed to encode response", http.StatusInternalServerError)
  44. return
  45. }
  46. }
  47. // GetSSHKeyByID handles the retrieval of a specific SSH key by ID
  48. func (h *SSHKeyHandler) GetSSHKeyByID(w http.ResponseWriter, r *http.Request) {
  49. vars := mux.Vars(r)
  50. keyID := vars["id"]
  51. log.Printf("Handling GET request for SSH key ID: %s from %s", keyID, r.RemoteAddr)
  52. var sshKey SSHKey
  53. err := config.OVHClient.Get("/me/sshKey/"+keyID, &sshKey)
  54. if err != nil {
  55. log.Printf("Error fetching SSH key %s: %v", keyID, err)
  56. http.Error(w, "Failed to fetch SSH key: "+err.Error(), http.StatusInternalServerError)
  57. return
  58. }
  59. log.Printf("Successfully retrieved SSH key: %s", keyID)
  60. w.Header().Set("Content-Type", "application/json")
  61. if err := json.NewEncoder(w).Encode(sshKey); err != nil {
  62. log.Printf("Error encoding SSH key response: %v", err)
  63. http.Error(w, "Failed to encode response", http.StatusInternalServerError)
  64. return
  65. }
  66. }