The main points of

Last article Serverless- to achieve a short URL service (a) to achieve a short link generation cloud function, this article completed the second half of the short link jump. The main contents to be paid attention to include:

  1. Tencent cloud function API call how to read the path parameters
  2. The difference between integrated response and transparent response in Tencent cloud function

Get the real URL from the requested short link

As mentioned above, the short links we generate are generated from integer ids using hashids library, so the process of obtaining the real URL is also very simple. You only need to call the decode method of Hashids to obtain the original integer ID, and then query the database with this as a parameter to obtain the real URL

Paste code directly

# -*- coding: utf8 -*-
from os import getenv
from hashids import Hashids
import json
from serverless_db_sdk import database


def main_handler(event, context):
    Read request parameters
    if "requestContext" not in event.keys():
        return {"errorCode": 410, "errorMsg": "event is not come from api gateway"}
    request = event["requestContext"]
    The path parameter in the cloud API call is read like this
    hash = event['pathParameters'] ['hash']
    hashid = Hashids(salt="bangbangbang")
    # decode get id
    auto_id = hashid.decode(hash) [0]print(auto_id, hash)

    Query url from data with id
    result_data = []
    sql_template = """SELECT url FROM bing.short_url where id = %s """
    connection = database("BING").connection(autocommit=False)
    try:
        cursor = connection.cursor()
        cursor.execute(sql_template, (auto_id))
        result = cursor.fetchone()
        url = result[0]
    finally:
        connection.close()
    
    Because to return 302 messages, it needs to be returned according to the integrated response format defined by Tencent Cloud
    return {
        "isBase64Encoded": False,
        "statusCode": 302,
        "headers": {"Location": url}
    }

Copy the code

The key to explain

Path Read path parameters

The way we generally use short urls after generating them is as follows:

http://domain name /{short link string}

Like a short link like this:

short.url/zv

Zv is the short string generated by us. To be able to use this type of API request in Tencent Cloud, it is necessary to configure the responding API in THE API gateway console as follows:

Then read the parameters in the cloud function as follows:

# hash is the name of the previously configured parameter
hash = event['pathParameters'] ['hash']
Copy the code

Integrated response and pass-through response

Simply put, a pass-through response only returns a 200 status code and passes the returned content as the body of the message to the front end, so ordinary function calls that return JSON data can use this method directly.

The integrated response can be customized to return HTTP status code, message and other content, we here is a short url jump, need to return 302 or 301 message, so must use the integrated response.

For details, please refer to the official document of Tencent Cloud:

Integrated response, which means that 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, error information {“errno”:403,”error”:”Invalid SCF response format. Please check your SCF response format.”} is displayed.

Pass-through response means that the API gateway passes the content returned by the cloud function directly to the API requester. Usually, the data format of this response is directly determined as JSON. The status code is defined according to the status of the function execution. The status code is 200 if the function is successfully executed. Through the transparent response, users can obtain the JSON format and parse the structure at the call location to obtain the content in the structure.

The sample

service-jmhm1hno-1256668370.gz.apigw.tencentcs.com/test/go/zv

After binding their own domain name, you can realize a short link jump service of your own