You can use HTTP handlers to efficiently process HTTP requests. When you invoke a function, Function Compute runs the handler that you specify in the function code to process requests. This topic describes the structure and characteristics of HTTP handlers for Go.

Sample code for using an HTTP handler

Import an official SDK library named aliyun/serverless/fc-runtime-go-sdk/fc for Go and implement the handler and main functions. Sample code:

package main

import (
    "context"
    "fmt"
    "net/http"
    "io/ioutil"

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

func HandleHttpRequest(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
  body, err := ioutil.ReadAll(req.Body)
  if err != nil {
    w.WriteHeader(http.StatusBadRequest)
    w.Header().Add("Content-Type", "text/plain")
    w.Write([]byte(err.Error()))
    return nil
  }
    w.WriteHeader(http.StatusOK)
    w.Header().Add("Content-Type", "text/plain")
    w.Write([]byte(fmt.Sprintf("Hi,%s! \n", body)))
    return nil
}

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

The following content describes the code snippets in the sample code:

  • package main: the main package. Each Go application contains a main package.
  • import: imports Function Compute dependencies. You need to import the following dependencies:
    • github.com/aliyun/fc-runtime-go-sdk/fc: the core library of Function Compute SDK for Go.
    • context: the context object of Function Compute SDK for Go.
    • net/http: provides the Request and ResponseWriter methods in the HTTP package for the HTTP handler.
  • HandleHttpRequest(ctx context.Context, w http.ResponseWriter, req *http.Request) error: the HTTP handler used to process HTTP requests. The handler contains the code to be run and involves the following parameters:
    • ctx context.Context: provides the runtime context information when a function is invoked. For more information, see Context.
    • w http.ResponseWriter: the response method of the HTTP handler. You can call this method to set the status code, response header, and response body. For more information, see the Response method section.
    • req *http. Request: the request method of the HTTP handler. You can call this method to set the request line, request header, and request body. For more information, see Request struct.
    • w.WriteHeader(http.StatusOK): Specify the HTTP status code of the response.
    • w.Header(). Add("Content-Type", "text/plain"): Specify the response header.
    • w.Write([]byte(fmt.Sprintf("Hi,%s! \n", body))): Specify the response body.
    • return nil: returns a simple error message. If nil is returned, no error occurs. If an error message is returned, a function error occurs.
  • func main(): the entry point for running function code in Function Compute. A Go application must contain the main function. To run your application in Function Compute, invoke the fc.StartHttp(HandleHttpRequest) function in the main() function.
    Important The methods used to start an HTTP handler and an event handlers are different. To start an event handler, invoke the fc.Start function in the main function. To start an HTTP handler, invoke the fc.StartHttp function in the main function.

Definition

An HTTP handler for Go is defined based on Handler interface for HTTP requests in the Go standard library but contains an additional context parameter. Syntax of an HTTP handler:

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

An HTTP handler consists of the following three objects:

  • context: provides the runtime context information when a function is invoked in Function Compute. For more information, see Context.
  • http.Request: the request struct. For more information, see Request struct.
  • http.ResponseWriter: the response method. For more information, see Response method.

Request struct

http.Request is the HTTP object defined in the Go standard library. The following table describes the parameters that are supported by the http.Request object.

ParameterTypeDescription
MethodStringThe HTTP request method, such as PUT, POST, or DELETE.
URL*url.URLThe request URL.
Headerhttp.HeaderThe key-value pair of the HTTP request header.
Bodyio.ReadCloserThe request struct.
ContentLengthInt64The data length in the request struct.

Response method

The following sample code shows the three methods declared by http.ResponseWriter:

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

Note:

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

Limits

  • Request limits

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

    FieldLimitsHTTP status codeError
    headersThe total size of the keys and values in the request headers cannot exceed 4 KB. 400InvalidArgument
    pathThe total size of the request path and query parameters cannot exceed 4 KB.
    bodyThe total size of the body of a synchronous invocation request cannot exceed 32 MB. The total size of the body of an asynchronous invocation request cannot exceed 128 KB.
  • Response limits

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

    FieldLimitsHTTP status codeError
    headersThe total size of the keys and values in the response headers cannot exceed 4 KB. 502BadResponse
    bodyThe total size of the body of a synchronous invocation response cannot exceed 16 MB. The total size of the body of an asynchronous invocation response cannot exceed 128 KB.

Context

For more information about the context, see Context.