Skip to content

Commit 8e27fa2

Browse files
committed
Merge remote-tracking branch 'origin/master' into i18n-pt-br
# Conflicts: # site/astro.config.mjs
2 parents a978f9b + a225a56 commit 8e27fa2

60 files changed

Lines changed: 7319 additions & 3 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

site/astro.config.mjs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ export default defineConfig({
1515
root: { label: 'English', lang: 'en' },
1616
'zh-cn': { label: '简体中文', lang: 'zh-CN' },
1717
ja: { label: '日本語', lang: 'ja' },
18+
es: { label: 'Español', lang: 'es' },
1819
'pt-br': { label: 'Português', lang: 'pt-BR' },
1920
},
2021
logo: {
@@ -104,9 +105,9 @@ export default defineConfig({
104105
// Autogenerated from the content dirs — new pages appear automatically,
105106
// ordered by each page's `sidebar.order` frontmatter.
106107
sidebar: [
107-
{ label: 'Guide', translations: { 'zh-CN': '指南', ja: 'ガイド', 'pt-BR': 'Guia' }, items: [{ autogenerate: { directory: 'guide' } }] },
108-
{ label: 'Middleware', translations: { 'zh-CN': '中间件', ja: 'ミドルウェア', 'pt-BR': 'Middleware' }, items: [{ autogenerate: { directory: 'middleware' } }] },
109-
{ label: 'Cookbook', translations: { 'zh-CN': '示例', ja: 'クックブック', 'pt-BR': 'Receitas' }, items: [{ autogenerate: { directory: 'cookbook' } }] },
108+
{ label: 'Guide', translations: { 'zh-CN': '指南', ja: 'ガイド', es: 'Guía', 'pt-BR': 'Guia' }, items: [{ autogenerate: { directory: 'guide' } }] },
109+
{ label: 'Middleware', translations: { 'zh-CN': '中间件', ja: 'ミドルウェア', es: 'Middleware', 'pt-BR': 'Middleware' }, items: [{ autogenerate: { directory: 'middleware' } }] },
110+
{ label: 'Cookbook', translations: { 'zh-CN': '示例', ja: 'クックブック', es: 'Recetario', 'pt-BR': 'Receitas' }, items: [{ autogenerate: { directory: 'cookbook' } }] },
110111
],
111112
// tune the built-in code theme toward our terminal palette
112113
expressiveCode: { themes: ['github-dark', 'github-light'] },
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
---
2+
title: Auto TLS
3+
description: Obtén y renueva automáticamente certificados TLS desde Let's Encrypt.
4+
sidebar:
5+
order: 3
6+
---
7+
8+
Esta receta obtiene automáticamente certificados TLS para un dominio desde Let's Encrypt.
9+
Configura un `StartConfig` con el `TLSConfig` del manager autocert y escucha en el
10+
puerto `443`.
11+
12+
Abre `https://<DOMAIN>`. Si todo está configurado correctamente, deberías ver
13+
un mensaje de bienvenida servido sobre TLS.
14+
15+
:::tip
16+
- Para mayor seguridad, especifica una host policy en el manager autocert.
17+
- Cachea certificados para evitar alcanzar los [rate limits de Let's Encrypt](https://letsencrypt.org/docs/rate-limits).
18+
- Para redirigir tráfico HTTP a HTTPS, usa el [middleware redirect](/es/middleware/redirect/#https-redirect).
19+
:::
20+
21+
## Servidor
22+
23+
```go
24+
package main
25+
26+
import (
27+
"context"
28+
"crypto/tls"
29+
"errors"
30+
"log/slog"
31+
"net/http"
32+
"os"
33+
34+
"golang.org/x/crypto/acme"
35+
36+
"github.com/labstack/echo/v5"
37+
"github.com/labstack/echo/v5/middleware"
38+
"golang.org/x/crypto/acme/autocert"
39+
)
40+
41+
func main() {
42+
e := echo.New()
43+
e.Logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))
44+
45+
e.Use(middleware.Recover())
46+
e.Use(middleware.RequestLogger())
47+
48+
e.GET("/", func(c *echo.Context) error {
49+
return c.HTML(http.StatusOK, `
50+
<h1>Welcome to Echo!</h1>
51+
<h3>TLS certificates automatically installed from Let's Encrypt :)</h3>
52+
`)
53+
})
54+
55+
m := &autocert.Manager{
56+
Prompt: autocert.AcceptTOS,
57+
HostPolicy: autocert.HostWhitelist("example.com", "www.example.com"),
58+
// Cache certificates to avoid issues with rate limits (https://letsencrypt.org/docs/rate-limits)
59+
Cache: autocert.DirCache("/var/www/.cache"),
60+
// Email: "[email protected]", // optional but recommended
61+
}
62+
63+
sc := echo.StartConfig{
64+
Address: ":443",
65+
TLSConfig: m.TLSConfig(),
66+
}
67+
if err := sc.Start(context.Background(), e); err != nil {
68+
e.Logger.Error("failed to start server", "error", err)
69+
}
70+
}
71+
```
72+
73+
## Usar un servidor HTTP personalizado
74+
75+
Si necesitas control total sobre `http.Server`, conecta el manager autocert a un
76+
`tls.Config` personalizado:
77+
78+
```go
79+
func customHTTPServer() {
80+
e := echo.New()
81+
e.Use(middleware.Recover())
82+
e.Use(middleware.RequestLogger())
83+
e.GET("/", func(c *echo.Context) error {
84+
return c.HTML(http.StatusOK, `
85+
<h1>Welcome to Echo!</h1>
86+
<h3>TLS certificates automatically installed from Let's Encrypt :)</h3>
87+
`)
88+
})
89+
90+
autoTLSManager := autocert.Manager{
91+
Prompt: autocert.AcceptTOS,
92+
// Cache certificates to avoid issues with rate limits (https://letsencrypt.org/docs/rate-limits)
93+
Cache: autocert.DirCache("/var/www/.cache"),
94+
//HostPolicy: autocert.HostWhitelist("<DOMAIN>"),
95+
}
96+
s := http.Server{
97+
Addr: ":443",
98+
Handler: e, // set Echo as handler
99+
TLSConfig: &tls.Config{
100+
//Certificates: nil, // <-- s.ListenAndServeTLS will populate this field
101+
GetCertificate: autoTLSManager.GetCertificate,
102+
NextProtos: []string{acme.ALPNProto},
103+
},
104+
//ReadTimeout: 30 * time.Second, // use custom timeouts
105+
}
106+
if err := s.ListenAndServeTLS("", ""); err != nil && !errors.Is(err, http.ErrServerClosed) {
107+
e.Logger.Error("failed to start server", "error", err)
108+
}
109+
}
110+
```
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
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

Comments
 (0)