Do Google Cloud Platform HTTP Functions Support Route Parameters?

后端 未结 4 1807
野性不改
野性不改 2021-02-20 16:25

This is a bit simpler a question than I tend to like to come here with but I\'ve been driving myself up the wall trying to find an answer to this and I absolutely cannot-

<
4条回答
  •  逝去的感伤
    2021-02-20 17:15

    I was able to reach out to the support group for this and it appears that yes, this is supported - you just have to use req.path in order to pull the full path and then parse it in some way (I used path-to-regexp)

    Sample code:

    exports.myFunction = function(req, res) {
        var keys = [];
        var re = pathToRegexp('/:paramA/:paramB/not-a-param/:paramC/also-not-a-param/:paramD?', keys, {strict: false});
        var pathVars = re.exec(req.path);
        if (pathVars) {
            console.log(JSON.stringify(pathVars));
            var paramA = pathVars[1];
            var paramB = pathVars[2];
            var paramC = pathVars[3];
            var paramD = pathVars[4];
            // Do stuff with the rest of your functionality here
            res.status(200).send('Whatever you wanna send');
        }
    }
    

    The command line code to deploy this would then look something like gcloud beta functions deploy myFunction --stage-bucket --trigger-http (Full documentation for this command here). Your new endpoint URL will then be https://-.cloudfunctions.net/myFunction, and you can then append subsequent query or route parameters to it when actually making your call (e.g., making a get call to https://-.cloudfunctions.net/myFunction/paramA/paramB/not-a-param/paramC/also-not-a-param/paramD).

    Please note that:

    1. Your function should be exported under the same name as used in the CLI unless you use the --entry-point flag. This name will be used in your resulting URL.
    2. The --stage-bucket command is optional, but I've always used it.
    3. Cloud Functions will automatically look to a file named index.js or function.js to find your function, but if you provide a package.json file which contains a main entry, then Cloud Functions will look for it instead.
    4. This will, I assume, leave beta at some point, at which you should update to the new command tools.

提交回复
热议问题