Os aplicativos geralmente precisam servir arquivos estáticos, como JavaScript, imagens e CSS, além de lidar com solicitações dinâmicas. Os aplicativos no ambiente padrão podem fornecer arquivos estáticos de uma opção do Google Cloud, como Cloud Storage, servi-los diretamente ou usar uma rede de entrega de conteúdo (CDN) de terceiros. Hospedar seu site estático no Google Cloud pode custar menos do que usar uma hospedagem tradicional provedor, já que o Google Cloud oferece um nível gratuito
## Servindo arquivos do Cloud Storage
O Cloud Storage pode hospedar ativos estáticos para aplicativos da web dinâmicos. Os benefícios de usar o Cloud Storage em vez de servir diretamente do seu aplicativo incluem:
- Cloud Storage funciona essencialmente como uma rede de entrega de conteúdo. Isso não requer nenhuma configuração especial porque, por padrão, qualquer objeto legível é armazenado em cache na rede global de armazenamento em nuvem
- A carga do seu aplicativo será reduzida ao descarregar ativos estáticos de serviço para o Cloud Storage. Dependendo de quantos ativos estáticos você possui e da frequência de acesso, isso pode reduzir significativamente o custo de execução do seu aplicativo
- As cobranças de largura de banda para acessar o conteúdo geralmente podem ser menores com o Cloud Storage
Você pode fazer upload de seus ativos para o Cloud Storage usando o
ferramenta de linha de comando gsutil
ou a API Cloud Storage
A Google Cloud Client Library fornece um cliente Go 1.11 idiomático para o Cloud Storage, para armazenar e recuperar dados com o Cloud Storage em um aplicativo do App Engine
Exemplo de exibição de um intervalo do Cloud Storage
Este exemplo simples cria um bucket do Cloud Storage e carrega ativos estáticos usando o Google Cloud CLI:
Crie um balde. É comum, mas não obrigatório, nomear seu bucket com o ID do projeto. O nome do bucket deve ser globalmente exclusivo
gsutil mb gsyour-bucket-name>Defina a ACL para conceder acesso de leitura aos itens no bucket
gsutil defacl set public-read gsyour-bucket-name>Carregue itens no bucket. o
rsynccommand é normalmente a maneira mais rápida e fácil de carregar e atualizar ativos. Você também pode usar
cp
gsutil -m rsync -r ./static gsyour-bucket-name>/static
Agora você pode acessar seus ativos estáticos via
httpsstorage.googleapis.com//static
For more details on how to use Cloud Storage to serve static assets, including how to serve from a custom domain name, refer to How to Host a Static Website
Serving files from other Google Cloud services
You also have the option of using Cloud CDN or other Google Cloud storage services
## Serving files directly from your app
To serve static files for Go 1.11 in the standard environment,
you define the handlers in your
app.yaml file using either the
static_dir
or
static_files
elements
The content in the static files or static directories are unaffected
by the scaling settings in your
app.yaml file. Requests to static files or
static directories are handled by the App Engine infrastructure
directly, and do not reach the language runtime of the application
Configuring your static file handlers
To configure your app to serve the
./public directory from the
/static URL,
you define a handler in your
app.yaml file
The following demonstrates how to serve the static files of a sample
app's
./public directory. The template for this app's
index.html page
instructs the browser to load the
main.css file, for example:
/css/main.css">
The
./public directory is defined in the
static_dir element of the project's
app.yaml file:
handlers: - url: /favicon\.ico static_files: favicon.ico upload: favicon\.ico - url: /static static_dir: public - url:secure: always redirect_http_response_code: 301 script: auto
The
handlers section in the above example handles three URL patterns:
The
/favicon.icohandler maps a request specifically for
/favicon.icoto a file named
favicon.icoin the app's root directory
The
/statichandler maps requests for URLs that start with
/static. When App Engine receives a request for a URL beginning with
/static, it maps the remainder of the path to files in the
./publicdirectory. If an appropriate file is found in the directory, the contents of that file are returned to the client
The
handler matches all other URLs and directs them to your app
URL path patterns are tested in the order they appear in
app.yaml, therefore
the pattern for your static files should be defined before the
pattern
For more information, see the
app.yaml
reference
## Serving from a third-party content delivery network
You can use any external third-party CDN to serve your static files and cache dynamic requests but your app might experience increased latency and cost
For improved performance, you should use a third-party CDN that supports CDN Interconnect.