instance.go 908 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package middleware
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/gofrs/uuid"
  6. "github.com/labstack/echo/v4"
  7. "net/http"
  8. )
  9. func InstanceId() echo.MiddlewareFunc {
  10. return func(next echo.HandlerFunc) echo.HandlerFunc {
  11. return func(c echo.Context) error {
  12. s := c.Request().Header.Get("X-Instance-ID")
  13. if s == "" {
  14. return echo.NewHTTPError(http.StatusForbidden, "missing or malformed instance id")
  15. }
  16. id, err := uuid.FromString(s)
  17. if err != nil {
  18. return echo.NewHTTPError(http.StatusForbidden, "missing or malformed instance id")
  19. }
  20. value := context.WithValue(c.Request().Context(), keyInstanceId, id)
  21. c.SetRequest(c.Request().WithContext(value))
  22. return next(c)
  23. }
  24. }
  25. }
  26. func GetInstanceId(ctx context.Context) (uuid.UUID, error) {
  27. id, ok := ctx.Value(keyInstanceId).(uuid.UUID)
  28. if !ok {
  29. return uuid.Nil, fmt.Errorf("missing or malformed instance id")
  30. }
  31. return id, nil
  32. }