Linguagem .NET

É possível escrever a função usando diferentes linguagens .NET (C#, Visual Basic ou F#). A tarefa principal é a mesma em todas as linguagens. Você cria uma classe implementando uma das interfaces do Functions Framework:

Este documento fornece exemplos de F# e Visual Basic.

Modelos

Para executar os exemplos deste documento, você usará os modelos:

  1. Instale o SDK .NET.

  2. Instale o pacote de modelos:

    dotnet new install Google.Cloud.Functions.Templates
    

Os modelos são fornecidos para os três tipos de funções em C# (padrão), F# e Visual Basic. Ao criar um novo projeto usando um modelo, especifique -lang f# para criar um projeto F# ou -lang vb para criar um projeto Visual Basic. Por exemplo, para criar uma nova função sem tipo do CloudEvent para Visual Basic, execute:

dotnet new gcf-untyped-event -lang vb

Para exemplos de F# e Visual Basic, consulte Linguagens .NET.

Exemplos de função HTTP

Você usa funções HTTP para invocar sua função por meio de uma solicitação HTTP(S). Os exemplos a seguir geram a mensagem "Hello World!"

F#

namespace HelloWorldFSharp

open Google.Cloud.Functions.Framework
open Microsoft.AspNetCore.Http

type Function() =
    interface IHttpFunction with
        member this.HandleAsync context =
            async {
                do! context.Response.WriteAsync "Hello World!" |> Async.AwaitTask
            } |> Async.StartAsTask :> _

Visual Basic

Imports Google.Cloud.Functions.Framework
Imports Microsoft.AspNetCore.Http

Public Class CloudFunction
    Implements IHttpFunction

    Public Async Function HandleAsync(context As HttpContext) As Task Implements IHttpFunction.HandleAsync
        Await context.Response.WriteAsync("Hello World!")
    End Function
End Class

Arquivos de projeto para exemplos de HTTP

Veja os arquivos de projeto dos exemplos acima:

F#

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <Compile Include="Function.fs" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Google.Cloud.Functions.Hosting" Version="2.2.0" />
  </ItemGroup>
</Project>

Visual Basic

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <RootNamespace>HelloWorldVb</RootNamespace>
    <TargetFramework>net6.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Google.Cloud.Functions.Hosting" Version="2.2.0" />
  </ItemGroup>
</Project>

Como implantar as funções HTTP

F#

gcloud functions deploy fsharp-helloworld --entry-point HelloWorldFSharp.Function --runtime dotnet6 --trigger-http --allow-unauthenticated

Visual Basic

gcloud functions deploy vb-helloworld --entry-point HelloWorldVb.CloudFunction --runtime dotnet6 --trigger-http --allow-unauthenticated

Exemplos do CloudEvent

Use funções do CloudEvent quando quiser que sua função do Cloud seja invocada indiretamente em resposta a um evento assíncrono, como uma mensagem em um tópico do Pub/Sub, uma alteração em um bucket do Cloud Storage ou um evento do Firebase.

F#

namespace HelloPubSubFSharp

open Google.Cloud.Functions.Framework
open Google.Events.Protobuf.Cloud.PubSub.V1
open Microsoft.Extensions.Logging
open System
open System.Threading.Tasks

type Function(logger: ILogger<Function>) =
    interface ICloudEventFunction<MessagePublishedData> with
        member this.HandleAsync(cloudEvent, data, cancellationToken) =
            let nameFromMessage = data.Message.TextData
            let name = if String.IsNullOrEmpty(nameFromMessage) then "world" else nameFromMessage
            logger.LogInformation("Hello {name}", name)
            Task.CompletedTask

Visual Basic

Imports System.Threading
Imports CloudNative.CloudEvents
Imports Google.Cloud.Functions.Framework
Imports Google.Events.Protobuf.Cloud.PubSub.V1
Imports Microsoft.Extensions.Logging

Public Class CloudFunction
    Implements ICloudEventFunction(Of MessagePublishedData)

    Private _logger As ILogger

    Public Sub New(ByVal logger As ILogger(Of CloudFunction))
        _logger = logger
    End Sub

    Public Function HandleAsync(cloudEvent As CloudEvent, data As MessagePublishedData, cancellationToken As CancellationToken) As Task _
        Implements ICloudEventFunction(Of MessagePublishedData).HandleAsync

        Dim nameFromMessage = data.Message?.TextData
        Dim name = If(String.IsNullOrEmpty(nameFromMessage), "world", nameFromMessage)
        _logger.LogInformation("Hello {name}", name)

        Return Task.CompletedTask
    End Function
End Class

Como implantar funções do CloudEvent

F#

gcloud functions deploy fsharp-hello-pubsub --entry-point HelloPubSubFSharp.Function --runtime dotnet6 --trigger-topic my-topic --allow-unauthenticated

Visual Basic

gcloud functions deploy vb-hello-pubsub --entry-point HelloPubSubVb.CloudFunction --runtime dotnet6 --trigger-topic my-topic --allow-unauthenticated

Testar os exemplos do CloudEvent

É possível testar os exemplos do CloudEvent da seguinte maneira:

  1. Publique uma mensagem no tópico do Pub/Sub para acionar a função:

    gcloud pubsub topics publish my-topic --message Flurry
  2. Veja os registros:

    gcloud functions logs read --limit 10

Você verá algo assim, com uma mensagem que inclui o nome publicado no tópico do Pub/Sub:

D      my-function  ...  Function execution started
I      my-function  ...  Hello Flurry!
D      my-function  ...  Function execution took 39 ms, finished with status: 'ok'