Програмам часто потрібно обслуговувати статичні файли, такі як JavaScript, зображення та CSS, на додаток до обробки динамічних запитів. Програми в стандартному середовищі можуть обслуговувати статичні файли з опції Google Cloud, як-от Cloud Storage, обслуговувати їх безпосередньо або використовувати сторонню мережу доставки вмісту (CDN). Розміщення вашого статичного сайту в Google Cloud може коштувати дешевше, ніж використання традиційного хостингу постачальника, оскільки Google Cloud надає безкоштовний рівень ## Обслуговування файлів із Cloud Storage Хмарне сховище може розміщувати статичні ресурси для динамічних веб-програм. Переваги використання хмарного сховища замість обслуговування безпосередньо з програми включають: - Хмарне сховище по суті працює як мережа доставки контенту. Для цього не потрібна спеціальна конфігурація, оскільки за замовчуванням будь-який читабельний об’єкт кешується в глобальній мережі Cloud Storage - Завантаження вашої програми буде зменшено шляхом перенесення обслуговуючих статичних ресурсів у Cloud Storage. Залежно від того, скільки у вас статичних ресурсів і частоти доступу, це може суттєво зменшити витрати на роботу програми - Плата за смугу пропускання для доступу до вмісту часто може бути нижчою з Cloud Storage Ви можете завантажити свої ресурси в хмарне сховище за допомогою інструмент командного рядка gsutil або API Cloud Storage Google Cloud Client Library надає ідіоматичний клієнт Go 1.11 для Cloud Storage для зберігання та отримання даних за допомогою Cloud Storage у програмі App Engine Приклад обслуговування з відра Cloud Storage Цей простий приклад створює відро Cloud Storage і завантажує статичні ресурси за допомогою Google Cloud CLI: Створіть відро. Зазвичай, але не обов’язково, називати сегмент за ідентифікатором проекту. Назва сегмента має бути глобально унікальною gsutil mb gsyour-bucket-name>Налаштуйте ACL, щоб надати доступ для читання до елементів у відрі gsutil defacl set public-read gsyour-bucket-name>Завантажте елементи у відро. The Команда rsynccommand зазвичай є найшвидшим і найпростішим способом завантаження та оновлення ресурсів. Ви також можете використовувати cp gsutil -m rsync -r ./static gsyour-bucket-name>/static Тепер ви можете отримати доступ до своїх статичних ресурсів через 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.