To use Go programming in Function Compute services, you need to define a Go function as the entry point. This topic describes the structure and features of the Go HTTP function.

HTTP function definition

For the definition of the HTTP function for Go, see handler interface in the Go standard library HTTP and add a context parameter. The following sample code shows you how to specify table names and column names in the CREATE TABLE statement:

function(ctx context.Context, w http.ResponseWriter, req *http.Request) error

The function definition contains the following three parts:

Request structure

http.Request are defined in the Go standard library HTTP. The following table lists the supported parameters and methods.

Parameter Type Description
Method String HTTP methods, such as PUT, POST, and DELETE.
URL *url.URL The information about the request address.
Header http.Header The key-value pair of the HTTP request header.
Body io.ReadCloser The request structure.
ContentLength Int64 The length of the request structure data.

Response interface

The three methods that implement the http.ResponseWriter declaration are as follows:

type ResponseWriter interface {
    Header() Header
    Write([]byte) (int, error)
    WriteHeader(statusCode int)
}

The format is described as follows:

  • WriteHeader(statusCode int): Set status code.
  • Header() Header: obtains and sets the response header information.
  • Write([]byte) (int, error): specifies the response body.

Limits

  • Request limits

    If a request exceeds any one of the following limits, the system returns the status code 400 and the error code InvalidArgument.

    Field Limit HTTP status code Error code
    headers The total size of the keys and values in the request header cannot exceed 4 KB. 400 InvalidArgument
    path The total size of the request path and queries parameter cannot exceed 4 KB.
    body The body of the HTTP response cannot exceed 6 MB.
  • Response limits

    If a response exceeds any one of the following limits, the system returns the status code 502 and the error code BadResponse.

    Field Limit HTTP status code Error code
    headers The total size of the keys and values in the response header cannot exceed 4 KB. 502 BadResponse
    body The body of the HTTP response cannot exceed 6 MB.

Go HTTP function example

The following code example demonstrates how to use the Go HTTP function.

package main

import (
    "context"
    "net/http"
    "github.com/aliyun/fc-runtime-go-sdk/fc"
)

func main() {
    fc.StartHttp(HandleHttpRequest)
}

func HandleHttpRequest(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
    w.WriteHeader(http.StatusOK)
    w.Header().Add("Content-Type", "text/plain")
    w.Write([]byte("hello, world!\n"))
    return nil
}