When programming with Go Function Compute, you need to define a function as an entry point from which your code will start to execute. This topic describes the structure and features of Go event functions.

Definition

In the code of Go language, you need to introduce the official SDK library github.com/aliyun/fc-runtime-go-sdk/fc, and you need to implement handler functions and main functions. The following sample code shows you how to specify table names and column names in the CREATE TABLE statement:

// hello_world.go
package main

import (
    "fmt"
    "github.com/aliyun/fc-runtime-go-sdk/fc"
)

func main() {
    fc.Start(HandleRequest)
}

func HandleRequest(event map[string]interface{}) (string, error) {
    fmt.Println("hello world")
    return "hello world", nil
}

Definition

Go is a compiled language. You need to directly upload executable binary files after local compilation. Different from the [file name].[function name] format of Python and Node.js, the function entry of Go can be set to [file name]. This file name refers to the name of the compiled binary file. When the function is called, the Function Compute platform directly starts execution from the file name configured at the function entry.

Definition of handler function parameters and return values

The handler functions in this example are as follows:

func HandleRequest(ctx context.Context, event map[string]interface{}) (string, error)

The handler function is the code that you need to execute. It contains the following content:

  • ctx context.Context: run time information, mainly RequestID, Function, Service, etc. Must be placed in the first parameter position. For more information, see context.go.
  • event map[string]interface{}: Event information, which can support the Go basic type and Struct type, can only be placed in the second parameter position.
  • (string, error): returns two values, a string and an error message. The first value supports the Go basic type and the Struct type.

handler supports the following formats:

  • func ()
  • func () error
  • func (TIn) error
  • func () (TOut, error)
  • func (TIn) (TOut, error)
  • func (context.Context) error
  • func (context.Context, TIn) error
  • func (context.Context) (TOut, error)
  • func (context.Context, TIn) (TOut, error)

Among them, the TIn and TOut are compatible with the encoding/json standard library.

event parameter

Notice If the event type is String, the parameter must be a string enclosed in double quotation marks.

If the parameter is JSON, the event can be defined as Struct or Map. Example:

package main

import (
    "fmt"
    "github.com/aliyun/fc-runtime-go-sdk/fc"
)

func main() {
    fc.Start(HandleRequest)
}

func HandleRequest(event map[string]interface{}) (string, error) {
    fmt.Printf("event: %v\n", event)
    fmt.Println("hello world! Hello, world! ")
    return "hello world! Hello, world! ", nil
}

context parameter

The following table lists the fields that the context contains.

Subparameter Description
Variables
RequestID The unique ID of the request for invoking the function. You can record this ID to easily query when a problem occurs.
Credentials A set of temporary keys obtained by the Function Compute service by assuming the service role is valid for 5 minutes. You can use Credentials in your code to access services such as OSS. This prevents you from encoding your AccessKey information in the function code. For more information, see Grant permissions across Alibaba Cloud accounts by using a RAM role.
Function The basic information of the invoked function, such as the name, handler, memory, and timeout period of the function.
Service The information about the service to which the currently called function belongs. The information includes the service name, the project and Logstore of Log Service, and the version and alias of the service. Where qualifier indicates the service version or alias specified when the function is invoked, and version_id indicates the service version actually invoked.
Region The ID of the region where the currently called function resides. For example, if it is called in the China (Shanghai) region, the region ID is cn-shanghai. For more information, see Endpoints.
AccountId The ID of the Alibaba Cloud account that calls the function.
Method
deadline The timeout period for function execution. The value is in the Unix timestamp format. Unit: milliseconds.

Examples

The handler of the function must contain context parameters. Insert the preceding variable information into the context Value. Then, you need to import github.com/aliyun/fc-runtime-go-sdk/fccontext and get the fccontext through the fccontext.FromContext method. Examples:

package main

import (
    "context"
    "encoding/json"
    "log"    
    "github.com/aliyun/fc-runtime-go-sdk/fc"
    "github.com/aliyun/fc-runtime-go-sdk/fccontext"
)

func main() {
    fc.Start(echoContext)
}

func echoContext(ctx context.Context) (string, error) {
    fctx, _ := fccontext.FromContext(ctx)
    log.Println(fctx.AccountId)
    log.Printf("%#v\n", fctx)
    res, _ := json.Marshal(fctx)
    return string(res), nil
}

The following example shows how to use the deadline to get the remaining execution time of the function.

package main

import (
    "context"
    "fmt"
    "log"
    "time"    
    "github.com/aliyun/fc-runtime-go-sdk/fc"
)

func LongRunningHandler(ctx context.Context) (string, error) {
    deadline, _ := ctx.Deadline()
    fmt.Printf("now: %s\ndeadline: %s\n", time.Now().String(), deadline.String())
    deadline = deadline.Add(-100 * time.Millisecond)
    timeoutChannel := time.After(time.Until(deadline))

    for {

        select {

        case <-timeoutChannel:
            return "Finished before timing out.", nil

        default:
            log.Print("hello!")
            time.Sleep(50 * time.Millisecond)
        }
    }
}

func main() {
    fc.Start(LongRunningHandler)
}