Tutorial HTTP


Tutorial sederhana ini menunjukkan penulisan, deployment, dan pemicuan HTTP Cloud Run function.

Tujuan

Biaya

Dalam dokumen ini, Anda akan menggunakan komponen Google Cloudyang dapat ditagih berikut:

  • Cloud Run functions

Untuk membuat perkiraan biaya berdasarkan proyeksi penggunaan Anda, gunakan kalkulator harga.

Pengguna Google Cloud baru mungkin memenuhi syarat untuk mendapatkan uji coba gratis.

Sebelum memulai

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Functions and Cloud Build APIs.

    Enable the APIs

  5. Install the Google Cloud CLI.

  6. Jika Anda menggunakan penyedia identitas (IdP) eksternal, Anda harus login ke gcloud CLI dengan identitas gabungan Anda terlebih dahulu.

  7. Untuk melakukan inisialisasi gcloud CLI, jalankan perintah berikut:

    gcloud init
  8. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  9. Verify that billing is enabled for your Google Cloud project.

  10. Enable the Cloud Functions and Cloud Build APIs.

    Enable the APIs

  11. Install the Google Cloud CLI.

  12. Jika Anda menggunakan penyedia identitas (IdP) eksternal, Anda harus login ke gcloud CLI dengan identitas gabungan Anda terlebih dahulu.

  13. Untuk melakukan inisialisasi gcloud CLI, jalankan perintah berikut:

    gcloud init
  14. Jika Anda sudah menginstal gcloud CLI, update dengan menjalankan perintah berikut:

    gcloud components update
  15. Siapkan lingkungan pengembangan Anda.
  16. Menyiapkan aplikasi

    1. Clone repositori aplikasi contoh ke komputer lokal Anda:

      Node.js

      git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

      Atau, Anda dapat mendownload contoh dalam file ZIP dan mengekstraknya.

      Python

      git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git

      Atau, Anda dapat mendownload contoh dalam file ZIP dan mengekstraknya.

      Go

      git clone https://github.com/GoogleCloudPlatform/golang-samples.git

      Atau, Anda dapat mendownload contoh dalam file ZIP dan mengekstraknya.

      Java

      git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git

      Atau, Anda dapat mendownload contoh sebagai file ZIP dan mengekstraknya.

      Ruby

      git clone https://github.com/GoogleCloudPlatform/ruby-docs-samples.git

      Atau, Anda dapat mendownload contoh dalam file ZIP dan mengekstraknya.

    2. Ubah ke direktori yang berisi kode contoh fungsi Cloud Run:

      Node.js

      cd nodejs-docs-samples/functions/helloworld/

      Python

      cd python-docs-samples/functions/helloworld/

      Go

      cd golang-samples/functions/helloworld/

      Java

      cd java-docs-samples/functions/helloworld/helloworld/

      Ruby

      cd ruby-docs-samples/functions/helloworld/

    3. Lihat kode contoh:

      Node.js

      const functions = require('@google-cloud/functions-framework');
      
      // Register an HTTP function with the Functions Framework that will be executed
      // when you make an HTTP request to the deployed function's endpoint.
      functions.http('helloGET', (req, res) => {
        res.send('Hello World!');
      });

      Python

      import functions_framework
      
      @functions_framework.http
      def hello_get(request):
          """HTTP Cloud Function.
          Args:
              request (flask.Request): The request object.
              <https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data>
          Returns:
              The response text, or any set of values that can be turned into a
              Response object using `make_response`
              <https://flask.palletsprojects.com/en/1.1.x/api/#flask.make_response>.
          Note:
              For more information on how Flask integrates with Cloud
              Functions, see the `Writing HTTP functions` page.
              <https://cloud.google.com/functions/docs/writing/http#http_frameworks>
          """
          return "Hello World!"
      
      

      Go

      
      // Package helloworld provides a set of Cloud Functions samples.
      package helloworld
      
      import (
      	"fmt"
      	"net/http"
      )
      
      // HelloGet is an HTTP Cloud Function.
      func HelloGet(w http.ResponseWriter, r *http.Request) {
      	fmt.Fprint(w, "Hello, World!")
      }
      

      Java

      
      package functions;
      
      import com.google.cloud.functions.HttpFunction;
      import com.google.cloud.functions.HttpRequest;
      import com.google.cloud.functions.HttpResponse;
      import java.io.BufferedWriter;
      import java.io.IOException;
      
      public class HelloWorld implements HttpFunction {
        // Simple function to return "Hello World"
        @Override
        public void service(HttpRequest request, HttpResponse response)
            throws IOException {
          BufferedWriter writer = response.getWriter();
          writer.write("Hello World!");
        }
      }

      Ruby

      require "functions_framework"
      
      FunctionsFramework.http "hello_get" do |_request|
        # The request parameter is a Rack::Request object.
        # See https://www.rubydoc.info/gems/rack/Rack/Request
      
        # Return the response body as a string.
        # You can also return a Rack::Response object, a Rack response array, or
        # a hash which will be JSON-encoded into a response.
        "Hello World!"
      end

    Men-deploy fungsi

    Untuk men-deploy fungsi dengan pemicu HTTP, jalankan perintah berikut di direktori yang berisi kode contoh (atau untuk Java, file pom.xml):

    Node.js

    gcloud functions deploy helloGET \
    --runtime nodejs20 --trigger-http

    Gunakan flag --runtime untuk menentukan ID runtime dari versi Node.js yang didukung untuk menjalankan fungsi Anda.

    Python

    gcloud functions deploy hello_get \
    --runtime python312 --trigger-http

    Gunakan flag --runtime untuk menentukan ID runtime versi Python yang didukung untuk menjalankan fungsi Anda.

    Go

    gcloud functions deploy HelloGet \
    --runtime go121 --trigger-http

    Gunakan flag --runtime untuk menentukan ID runtime versi Go yang didukung untuk menjalankan fungsi Anda.

    Java

    gcloud functions deploy java-http-function \
    --entry-point functions.HelloWorld \
    --runtime java17 \
    --memory 512MB --trigger-http

    Gunakan flag --runtime untuk menentukan ID runtime versi Java yang didukung guna menjalankan fungsi Anda.

    Ruby

    gcloud functions deploy hello_get --runtime ruby33 --trigger-http

    Gunakan flag --runtime untuk menentukan ID runtime versi Ruby yang didukung untuk menjalankan fungsi Anda.

    Secara opsional, Anda dapat menggunakan flag --allow-unauthenticated untuk menjangkau fungsi tanpa autentikasi. Hal ini berguna untuk pengujian, tetapi sebaiknya jangan gunakan setelan ini dalam produksi kecuali Anda membuat situs atau API publik. Selain itu, fitur ini mungkin tidak berfungsi untuk Anda, bergantung pada setelan kebijakan perusahaan Anda. Baca bagian Mengautentikasi pemanggilan untuk mengetahui informasi selengkapnya tentang cara memanggil fungsi yang memerlukan autentikasi.

    Memicu fungsi

    Untuk membuat permintaan HTTP ke fungsi Anda, jalankan perintah berikut:

    Node.js

    curl "https://REGION-PROJECT_ID.cloudfunctions.net/helloGET" 

    Python

    curl "https://REGION-PROJECT_ID.cloudfunctions.net/hello_get" 

    Go

    curl "https://REGION-PROJECT_ID.cloudfunctions.net/HelloGet" 

    Java

    curl "https://REGION-PROJECT_ID.cloudfunctions.net/java-http-function" 

    Ruby

    curl "https://REGION-PROJECT_ID.cloudfunctions.net/hello_get" 

    di mana

    • REGION adalah region tempat fungsi Anda di-deploy. Fungsi ini akan terlihat di terminal Anda setelah fungsi selesai di-deploy.
    • PROJECT_ID adalah project ID Cloud Anda. Fungsi ini akan terlihat di terminal Anda setelah fungsi selesai di-deploy.

    Anda juga dapat membuka endpoint fungsi yang di-deploy di browser untuk melihat pesan "Halo Dunia!" .

    Pembersihan

    Agar tidak dikenakan biaya pada akun Google Cloud Anda untuk resource yang digunakan dalam tutorial ini, hapus project yang berisi resource tersebut, atau simpan project dan hapus setiap resource-nya.

    Menghapus project

    Cara termudah untuk menghilangkan penagihan adalah dengan menghapus project yang Anda buat untuk tutorial.

    Untuk menghapus project:

    1. In the Google Cloud console, go to the Manage resources page.

      Go to Manage resources

    2. In the project list, select the project that you want to delete, and then click Delete.
    3. In the dialog, type the project ID, and then click Shut down to delete the project.

    Menghapus fungsi

    Menghapus fungsi Cloud Run tidak akan menghapus resource apa pun yang tersimpan di Cloud Storage.

    Untuk menghapus fungsi Cloud Run yang Anda buat dalam tutorial ini, jalankan perintah berikut:

    Node.js

    gcloud functions delete helloGET 

    Python

    gcloud functions delete hello_get 

    Go

    gcloud functions delete HelloGet 

    Java

    gcloud functions delete java-http-function 

    Ruby

    gcloud functions delete hello_get 

    Anda juga dapat menghapus fungsi Cloud Run dari Google Cloud console.