|
| 1 | +--- |
| 2 | +title: CORS |
| 3 | +description: Habilita Cross-Origin Resource Sharing con una allow list o una función de origin personalizada. |
| 4 | +sidebar: |
| 5 | + order: 4 |
| 6 | +--- |
| 7 | + |
| 8 | +El [middleware CORS](/es/middleware/cors/) controla qué origins pueden acceder a tu API. |
| 9 | +Puedes pasar una lista fija de origins permitidos o proporcionar una función que decida |
| 10 | +por request. |
| 11 | + |
| 12 | +## Allow list de origins |
| 13 | + |
| 14 | +Pasa los origins permitidos directamente a `middleware.CORS`. |
| 15 | + |
| 16 | +```go |
| 17 | +package main |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "net/http" |
| 22 | + |
| 23 | + "github.com/labstack/echo/v5" |
| 24 | + "github.com/labstack/echo/v5/middleware" |
| 25 | +) |
| 26 | + |
| 27 | +var ( |
| 28 | + users = []string{"Joe", "Veer", "Zion"} |
| 29 | +) |
| 30 | + |
| 31 | +func getUsers(c *echo.Context) error { |
| 32 | + return c.JSON(http.StatusOK, users) |
| 33 | +} |
| 34 | + |
| 35 | +func main() { |
| 36 | + e := echo.New() |
| 37 | + e.Use(middleware.RequestLogger()) |
| 38 | + e.Use(middleware.Recover()) |
| 39 | + |
| 40 | + // CORS default |
| 41 | + // Allows requests from any origin wth GET, HEAD, PUT, POST or DELETE method. |
| 42 | + // e.Use(middleware.CORS("*")) |
| 43 | + |
| 44 | + // CORS restricted |
| 45 | + // Allows requests from any `https://labstack.com` or `https://labstack.net` origin |
| 46 | + e.Use(middleware.CORS("https://labstack.com", "https://labstack.net")) |
| 47 | + |
| 48 | + e.GET("/api/users", getUsers) |
| 49 | + |
| 50 | + sc := echo.StartConfig{Address: ":1323"} |
| 51 | + if err := sc.Start(context.Background(), e); err != nil { |
| 52 | + e.Logger.Error("failed to start server", "error", err) |
| 53 | + } |
| 54 | +} |
| 55 | +``` |
| 56 | + |
| 57 | +## Función de origin personalizada |
| 58 | + |
| 59 | +Para policies dinámicas, usa `CORSWithConfig` con `UnsafeAllowOriginFunc`. La |
| 60 | +función recibe el contexto del request y el origin, y devuelve el origin que se debe |
| 61 | +reflejar, si el request está permitido y un error opcional. |
| 62 | + |
| 63 | +```go |
| 64 | +package main |
| 65 | + |
| 66 | +import ( |
| 67 | + "context" |
| 68 | + "net/http" |
| 69 | + "strings" |
| 70 | + |
| 71 | + "github.com/labstack/echo/v5" |
| 72 | + "github.com/labstack/echo/v5/middleware" |
| 73 | +) |
| 74 | + |
| 75 | +var ( |
| 76 | + users = []string{"Joe", "Veer", "Zion"} |
| 77 | +) |
| 78 | + |
| 79 | +func getUsers(c *echo.Context) error { |
| 80 | + return c.JSON(http.StatusOK, users) |
| 81 | +} |
| 82 | + |
| 83 | +// allowOrigin takes the origin as an argument and returns: |
| 84 | +// - origin to add to the response Access-Control-Allow-Origin header |
| 85 | +// - whether the request is allowed or not |
| 86 | +// - an optional error. this will stop handler chain execution and return an error response. |
| 87 | +// |
| 88 | +// return origin, true, err // blocks request with error |
| 89 | +// return origin, true, nil // allows CSRF request through |
| 90 | +// return origin, false, nil // falls back to legacy token logic |
| 91 | +func allowOrigin(c *echo.Context, origin string) (string, bool, error) { |
| 92 | + // In this example we use a naive suffix check but we can imagine various |
| 93 | + // kind of custom logic. For example, an external datasource could be used |
| 94 | + // to maintain the list of allowed origins. |
| 95 | + if strings.HasSuffix(origin, ".example.com") { |
| 96 | + return origin, true, nil |
| 97 | + } |
| 98 | + return "", false, nil |
| 99 | +} |
| 100 | + |
| 101 | +func main() { |
| 102 | + e := echo.New() |
| 103 | + e.Use(middleware.RequestLogger()) |
| 104 | + e.Use(middleware.Recover()) |
| 105 | + |
| 106 | + // CORS restricted with a custom function to allow origins |
| 107 | + // and with the GET, PUT, POST or DELETE methods allowed. |
| 108 | + e.Use(middleware.CORSWithConfig(middleware.CORSConfig{ |
| 109 | + UnsafeAllowOriginFunc: allowOrigin, |
| 110 | + AllowMethods: []string{http.MethodGet, http.MethodPut, http.MethodPost, http.MethodDelete}, |
| 111 | + })) |
| 112 | + |
| 113 | + e.GET("/api/users", getUsers) |
| 114 | + |
| 115 | + sc := echo.StartConfig{Address: ":1323"} |
| 116 | + if err := sc.Start(context.Background(), e); err != nil { |
| 117 | + e.Logger.Error("failed to start server", "error", err) |
| 118 | + } |
| 119 | +} |
| 120 | +``` |
0 commit comments