background

Serverless is the hot technology and is considered the future of cloud computing. Especially in the field of front-end research and development, using Node to develop cloud functions can make front-end engineers more focused on business logic and realize the role change of full-stack engineers.

Serverless applies to event-triggered scenarios. Pull up and call the Serverless cloud function when an event occurs, such as a file upload, a message event in a message queue, a timer event, or an event on an IoT device. It can also be used for some file processing, such as image processing, audio and video processing, log analysis and other scenarios.

Of course, these events also include HTTP request events, which is a big application scenario for Serverless — HTTP Services, which implement back-end services based on HTTP applications, such as REST apis, BFF, and SSR services, as well as the implementation of business logic. In the direction of Serverless, major domestic manufacturers have basically entered and formed their own products, such as Ali’s mPaas and Tencent’s CloudBase. Let’s take a look at Tencent’s position on CloudBase:

Cloud Development (TCB) is a cloud native integrated development environment and tool platform provided by Tencent Cloud, providing developers with highly available, automatic and flexible expansion of back-end cloud services, including computing, storage, hosting and other Serverless capabilities. Can be used for cloud integration development a variety of end applications (small procedures, the public, Web applications, because the client, etc.), to help developers build and management the back-end services and cloud resources, avoiding the tedious server builds in the process of application development in ops, developers can focus on the business logic implementation, development threshold is lower and more efficient.

Practical examples

While the above description is somewhat abstract, let’s go through a practical example to see how convenient serverless technology can be. Since many applications are accessed via applets, I used Cloudbase for testing purposes to facilitate my own expansion and because CloudBase offers a free package. The content of the example is the common database CURD operation. We use Golang to quickly implement an interface to obtain personnel information in Cloudbase, and quickly deploy online to provide public network access.

Preparing the test environment

We need to first opened tencent cloud account, and landing CloudBase serverless console, console.cloud.tencent.com/scf/, at the same time to apply for opening a free cloud database MemFireDB memfiredb.com/, Finally, there is our own development machine. Here I am using the Docker container on Centos7. CloudBase and MemFireDB registration procedures are not described in detail here, you can follow the guide of the website to complete the operation step by step. This section describes how to configure the development environment

Get the image and use Docker Search to view the latest image

Use Docker pull to pull the image

After the image is successfully obtained, use Docker Images to view it

Use docker run-it/bin/bash starts the image and enters the image to operate. Here we also need to install the vim editor to develop the code

apt-get update
apt-get install vim
apt-get install lrzsz
Copy the code

At this point, all of our development and test environments are ready to go, and it’s time to write the code

Write the code

What Serverless pays attention to is that each cloud function is simple and short, so we only need one main.go, and the code content is as follows:

package main

import (
	"fmt"
	"context"
	"github.com/tencentyun/scf-go-lib/cloudfunction"
	"github.com/go-pg/pg/v10"
	"encoding/json"
)

type Persons struct {
	Id int `json:"id"`
	Name string `json:"name"`
}

type DefineEvent struct {
    // test event define
    Key1 string `json:"key1"`
    Key2 string `json:"key2"`
}

type Header struct {
	Content_Type string `json:"Content-Type"`
}

type Resp struct {
	IsBase64Encoded bool `json:"isBase64Encoded"`
	StatusCode int `json:"statusCode"`
	Headers Header `json:"headers"`
	Body string `json:"body"`
}

func hello(ctx context.Context, event DefineEvent) (Resp, error) {
	
	opt := pg.Options{
        // Enter your cloud database address, user name, database name, and password
		Addr:     "",
		User:     "",
		Password: "",
		Database: "",
		OnConnect: func(ctx context.Context, cn *pg.Conn) error {
			println("new connection created")
			return nil
		},
	}

	db := pg.Connect(&opt)
	defer db.Close()

	header := Header{Content_Type: "application/json"}
	resp := Resp {
	    IsBase64Encoded : false,
	    StatusCode : 200,
	    Headers : header,
	    Body : "hello world",}var persons []Persons
	err := db.Model(&persons).Select()
	iferr ! =nil {
		fmt.Println(err)
		return resp, err
	}

	personstr, err := json.Marshal(persons)
	resp.Body = string(personstr)


    respstr, _ := json.Marshal(resp)
    fmt.Println(respstr)
    return resp, nil
}

func main(a) {
    // Make the handler available for Remote Procedure Call by Cloud Function
    cloudfunction.Start(hello)
}

Copy the code

Compile to generate an executable and package it for deployment

go mod init tcb-postgres-golang
go mod tidy
GOOS=linux GOARCH=amd64 go build -o main main.go
zip main.zip main
Copy the code

The deployment of test

Now insert some data in MemFireDB via the online editor

Create the cloud function in CloudBase and upload the executable compiled in the previous step

Select Go1 as the running environment, event function as the function type, and “upload ZIP package locally” as the function code. Then select main.zip prepared in the previous step, and click “Finish” after filling it.

After the deployment is complete, the function management page is displayed. Click the “Test” button to see whether the function is running normally

Add trigger mode and select API gateway trigger. In order to facilitate the test, we can select “authentication exemption”, select “Get” as the request method, and finally click “Finish” button

Finally, you can see the call address of the interface, which you can access directly from the browser

The content returned by the browser

By now, our interface has been developed and deployed. We do not need to buy any cloud resources or install and deploy our own server, but only need to develop our own business code to quickly launch the service. The high availability and expansion behind the service are completely hosted by CloudBase platform.

Matters needing attention

SCF error :403, error: Invalid SCF response format. Please check your SCF response format.

The API gateway parses the returned content of the cloud function and constructs the HTTP response based on the parsed content. With integrated responses, you can control the status code, headers, and body content of the response autonomously through your code, and you can respond to content in custom formats, such as XML, HTML, JSON, and even JS content. When the integration response is used, the data structure must be returned according to the integration response of the API gateway trigger before it can be successfully parsed by the API gateway. Otherwise, {“errno”:403,”error”:”requestId XXX, Invalid SCF Response. Expected SCF Response Valid JSON.”} error information is displayed.

conclusion

This article introduces the background and scenario of Serverless, and demonstrates the convenience of Serverless by using CloudBase and the cloud database MemFireDB to quickly build an interface for querying personnel information. As described by CloudBase: To provide developers with highly available, automatically flexible and scalable back-end cloud services, including computing, storage, hosting and other Serverless capabilities, which can be used for cloud integrated development of multiple end applications (apts, public accounts, Web applications, Flutter clients, etc.), to help developers build and manage back-end services and cloud resources in a unified manner. The tedious server construction and operation and maintenance in the application development process are avoided. Developers can focus on the realization of business logic, with lower development threshold and higher efficiency.