instance.go 728 B

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