server.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package server
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. databasev1 "github.com/iwanhae/nodb/api/v1"
  8. "github.com/iwanhae/nodb/pkg/broadcaster"
  9. "github.com/labstack/echo/v4"
  10. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  11. "k8s.io/apimachinery/pkg/runtime"
  12. "sigs.k8s.io/controller-runtime/pkg/client"
  13. )
  14. type Server struct {
  15. client.Client
  16. Broadcaster broadcaster.Broadcaster[runtime.Object]
  17. }
  18. func (s *Server) delete(c echo.Context) error {
  19. ctx := c.Request().Context()
  20. dbType := c.Param("type")
  21. namespace := c.Param("namespace")
  22. name := c.Param("name")
  23. switch strings.ToLower(dbType) {
  24. case "postgresql":
  25. return s.Client.Delete(ctx, &databasev1.PostgreSQL{
  26. ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: name}},
  27. )
  28. default:
  29. return echo.NewHTTPError(http.StatusBadRequest)
  30. }
  31. }
  32. func (s *Server) create(c echo.Context) error {
  33. ctx := c.Request().Context()
  34. dbType := c.Param("type")
  35. switch strings.ToLower(dbType) {
  36. case "postgresql":
  37. obj := &databasev1.PostgreSQL{}
  38. if err := json.NewDecoder(c.Request().Body).Decode(obj); err != nil {
  39. return err
  40. }
  41. return s.Client.Create(ctx, obj)
  42. default:
  43. return echo.NewHTTPError(http.StatusBadRequest)
  44. }
  45. }
  46. func (s *Server) watchUpdates(c echo.Context) error {
  47. ctx := c.Request().Context()
  48. ch := s.Broadcaster.Subscribe()
  49. w := c.Response().Writer
  50. w.Header().Set("Content-Type", "text/event-stream")
  51. w.Header().Set("Cache-Control", "no-cache")
  52. w.Header().Set("Connection", "keep-alive")
  53. w.Header().Set("Access-Control-Allow-Origin", "*")
  54. flusher := w.(http.Flusher)
  55. {
  56. list := databasev1.PostgreSQLList{}
  57. if err := s.Client.List(ctx, &list); err != nil {
  58. return err
  59. }
  60. go func() {
  61. for _, item := range list.Items {
  62. ch <- &item
  63. }
  64. }()
  65. }
  66. go func() {
  67. <-c.Request().Context().Done()
  68. close(ch)
  69. }()
  70. for obj := range ch {
  71. fmt.Fprint(w, "data: ")
  72. json.NewEncoder(w).Encode(obj)
  73. fmt.Fprint(w, "\n\n")
  74. flusher.Flush()
  75. }
  76. return nil
  77. }