正式生产的Google Cloud Function是什么样的?

时间:2018-08-29 10:57:47

标签: go google-cloud-functions serverless faas

我刚刚开始使用Google Cloud Functions来进行整个无服务器操作,所有示例基本上都是“ Helloworld”。

package function

import (
    "net/http"
)

func F(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello, World!\n"))
}

生产就绪功能是什么样的?

1 个答案:

答案 0 :(得分:16)

鉴于提供者会为您进行扩展等事情,所以我要做的第一件事就是关注可观察性。你不知道你不知道什么。我喜欢添加自己的跟踪和结构化日志记录;记录到stdout的方法有很多不足。

package function

import (
    "context"
    "fmt"
    "net/http"
    "os"
    "sync"

    "cloud.google.com/go/logging"
    "contrib.go.opencensus.io/exporter/stackdriver"
    "contrib.go.opencensus.io/exporter/stackdriver/propagation"
    "go.opencensus.io/trace"
    "google.golang.org/genproto/googleapis/api/monitoredres"
)

var (
    logger *logging.Logger
    once   sync.Once
)

// configFunc sets the global configuration; it's overridden in tests.
var configFunc = defaultConfigFunc

func F(w http.ResponseWriter, r *http.Request) {
    once.Do(func() {
        if err := configFunc(); err != nil {
           panic(err)
        }
    })

    defer logger.Flush()

    ctx := r.Context()
    var span *trace.Span

    httpFormat := &propagation.HTTPFormat{}
    sc, ok := httpFormat.SpanContextFromRequest(r)
    if ok {
        ctx, span = trace.StartSpanWithRemoteParent(ctx, "helloworld", sc,
            trace.WithSampler(trace.AlwaysSample()),
            trace.WithSpanKind(trace.SpanKindServer),
        )
        defer span.End()
    }

    logger.Log(logging.Entry{
        Payload:  "Handling new HTTP request",
        Severity: logging.Info,
    })

    w.Write([]byte("Hello, World!\n"))
}

func defaultConfigFunc() error {
    var err error

    projectId := os.Getenv("GCP_PROJECT")
    if projectId == "" {
            return fmt.Errorf("GCP_PROJECT environment variable unset or missing")
    }

    functionName := os.Getenv("FUNCTION_NAME")
    if functionName == "" {
            return fmt.Errorf("FUNCTION_NAME environment variable unset or missing")
    }

    region := os.Getenv("FUNCTION_REGION")
    if region == "" {
        return fmt.Errorf("FUNCTION_REGION environment variable unset or missing")
    }

    stackdriverExporter, err := stackdriver.NewExporter(stackdriver.Options{ProjectID: projectId})
    if err != nil {
        return err
    }

    trace.RegisterExporter(stackdriverExporter)
    trace.ApplyConfig(trace.Config{DefaultSampler: trace.AlwaysSample()})

    client, err := logging.NewClient(context.Background(), projectId)
    if err != nil {
        return err
    }

    monitoredResource := monitoredres.MonitoredResource{
        Type: "cloud_function",
        Labels: map[string]string{
            "function_name": functionName,
            "region":        region,
        },
    }

    commonResource := logging.CommonResource(&monitoredResource)
    logger = client.Logger(functionName, commonResource)

    return nil
}

此外,请确保您提供了所有依赖性,您确实希望构建可复制。这些天我正在使用Go 1.11,以下对我有用:

$ mkdir helloworld
$ cd helloworld
$ vim function.go
$ echo "module github.com/kelseyhightower/helloworld" > go.mod
$ go mod vendor