Defina uma função handler em Go, compile-a como binário e configure o parâmetro Handler no console do Function Compute com o nome do binário. O Function Compute executa esse handler a cada invocação.
Para usar gatilhos HTTP ou nomes de domínio personalizados no acesso às funções, obtenha a struct da requisição antes de definir as respostas HTTP. Para mais informações, consulte Usar um gatilho HTTP para invocar uma função.
Início rápido
Importe o pacote SDK github.com/aliyun/fc-runtime-go-sdk/fc, implemente uma função handler e passe-a para fc.Start em main().
package main
import (
"fmt"
"context"
"github.com/aliyun/fc-runtime-go-sdk/fc"
)
type StructEvent struct {
Key string `json:"key"`
}
func HandleRequest(ctx context.Context, event StructEvent) (string, error) {
return fmt.Sprintf("hello, %s!", event.Key), nil
}
func main() {
fc.Start(HandleRequest)
}
Este handler aceita um evento JSON com o campo key e retorna uma string de saudação:
{
"key": "value"
}
Análise do código
|
Elemento |
Finalidade |
|
|
Pacote de entrada obrigatório para qualquer executável Go |
|
|
SDK do Function Compute para Go |
|
|
Fornece o contexto de runtime para a invocação da função |
|
|
Função handler: recebe um contexto e um evento tipado; retorna uma string e um erro |
|
|
Registra o handler no Function Compute e inicia o loop de runtime |
Saiba mais sobre o objeto Context e o Tratamento de erros.
Compilação e implantação
Inicialize um módulo Go e instale o SDK do Function Compute:
go mod init my-fc-function
go get github.com/aliyun/fc-runtime-go-sdk
Compile o handler como um binário Linux (o Function Compute roda em Linux):
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o main main.go
Configure o parâmetro Handler no console do Function Compute como main (nome do binário compilado). Crie uma função de evento.
Assinaturas de handler
Regras para handlers:
Deve ser uma função.
Aceita de 0 a 2 parâmetros de entrada. Se houver dois parâmetros, o primeiro deve ser
context.Context.Retorna de 0 a 2 valores. Um único valor de retorno deve ser do tipo
error. Dois valores de retorno devem tererrorcomo segundo elemento.
Assinaturas válidas:
func ()
func () error
func (InputType) error
func () (OutputType, error)
func (InputType) (OutputType, error)
func (context.Context) error
func (context.Context, InputType) error
func (context.Context) (OutputType, error)
func (context.Context, InputType) (OutputType, error)
InputType e OutputType devem ser compatíveis com encoding/json. O Function Compute usa json.Unmarshal para entrada e json.Marshal para saída. JSON Unmarshal.
Tipos de evento de entrada
Escolha um tipo de evento conforme o caso de uso:
|
Tipo de evento |
Caso de uso |
Exemplo |
|
Struct |
Eventos fortemente tipados com campos conhecidos |
|
|
|
Entrada de string bruta |
|
|
|
Eventos dinâmicos ou fracamente tipados |
Veja outros exemplos em fc-runtime-go-sdk/examples.
Handlers de gatilho HTTP
Para processar requisições HTTP de um gatilho HTTP ou domínio personalizado, use HTTPTriggerEvent e HTTPTriggerResponse do pacote events do SDK.
Processar eventos de gatilho HTTP
package main
import (
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"github.com/aliyun/fc-runtime-go-sdk/events"
"github.com/aliyun/fc-runtime-go-sdk/fc"
)
type HTTPTriggerEvent events.HTTPTriggerEvent
type HTTPTriggerResponse events.HTTPTriggerResponse
func (h HTTPTriggerEvent) String() string {
jsonBytes, err := json.MarshalIndent(h, "", " ")
if err != nil {
return ""
}
return string(jsonBytes)
}
func NewHTTPTriggerResponse(statusCode int) *HTTPTriggerResponse {
return &HTTPTriggerResponse{StatusCode: statusCode}
}
func (h *HTTPTriggerResponse) String() string {
jsonBytes, err := json.MarshalIndent(h, "", " ")
if err != nil {
return ""
}
return string(jsonBytes)
}
func (h *HTTPTriggerResponse) WithStatusCode(statusCode int) *HTTPTriggerResponse {
h.StatusCode = statusCode
return h
}
func (h *HTTPTriggerResponse) WithHeaders(headers map[string]string) *HTTPTriggerResponse {
h.Headers = headers
return h
}
func (h *HTTPTriggerResponse) WithIsBase64Encoded(isBase64Encoded bool) *HTTPTriggerResponse {
h.IsBase64Encoded = isBase64Encoded
return h
}
func (h *HTTPTriggerResponse) WithBody(body string) *HTTPTriggerResponse {
h.Body = body
return h
}
func HandleRequest(event HTTPTriggerEvent) (*HTTPTriggerResponse, error) {
fmt.Printf("event: %v\n", event)
if event.Body == nil {
return NewHTTPTriggerResponse(http.StatusBadRequest).
WithBody(fmt.Sprintf("the request did not come from an HTTP Trigger, event: %v", event)), nil
}
reqBody := *event.Body
if event.IsBase64Encoded != nil && *event.IsBase64Encoded {
decodedByte, err := base64.StdEncoding.DecodeString(*event.Body)
if err != nil {
return NewHTTPTriggerResponse(http.StatusBadRequest).
WithBody(fmt.Sprintf("HTTP Trigger body is not base64 encoded, err: %v", err)), nil
}
reqBody = string(decodedByte)
}
return NewHTTPTriggerResponse(http.StatusOK).WithBody(reqBody), nil
}
func main() {
fc.Start(HandleRequest)
}
Este handler lê o corpo da requisição de HTTPTriggerEvent, decodifica-o de Base64 se necessário e o devolve como resposta. As structs vêm de github.com/aliyun/fc-runtime-go-sdk/events. Usar um gatilho HTTP para invocar uma função.
Invocar a função
Pré-requisitos
Verifique se você tem:
Uma função criada em runtime Go com o código de handler anterior
Um gatilho HTTP configurado para a função
Procedimento
Faça login no console do Function Compute. No painel de navegação à esquerda, clique em Functions.
Na barra de navegação superior, selecione uma região. Na página Functions, clique na função desejada.
Clique em Triggers e copie o endpoint público do gatilho HTTP.
-
Envie uma requisição para o endpoint:
curl -i "https://http-trigger-demo.cn-shanghai.fcapp.run" -d "Hello FC!"
Se o Authentication Method for No Authentication, chame a função diretamente com curl ou Postman.
Se estiver definido como Signature Authentication ou JWT Authentication, inclua as credenciais necessárias. Autenticação.
Solucionar erros de Test Function
Este handler espera entrada de gatilho HTTP. O botão Test Function envia um payload de evento padrão, gerando um erro 400:
{
"statusCode": 400,
"body": "the request did not come from an HTTP Trigger, event: {\n \"version\": null,\n \"rawPath\": null,\n \"headers\": null,\n \"queryParameters\": null,\n \"body\": null,\n \"isBase64Encoded\": null,\n \"requestContext\": null\n}"
}
Para inspecionar o evento bruto independentemente da origem, use um handler com []byte:
// GetRawRequestEvent returns the raw event as the response body
func GetRawRequestEvent(event []byte) (*HTTPTriggerResponse, error) {
fmt.Printf("raw event: %s\n", string(event))
return NewHTTPTriggerResponse(http.StatusOK).WithBody(string(event)), nil
}
func main() {
fc.Start(GetRawRequestEvent)
}