Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Go and AzureFunctions to build serverless applications

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to use Go and AzureFunctions to build serverless applications". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's ideas to study and learn "how to use Go and AzureFunctions to build serverless applications".

The Webhook backend is a popular use case for the FaaS (function as a service) platform. They can be used in many use cases, such as sending customer notifications to respond with interesting GIF! Using the Serverless function, it is convenient to encapsulate the webhook function and expose it as an HTTP endpoint. In this article, you will learn how to use Azure Functions and Go to implement Slack applications as serverless backends. You can extend the Slack platform and integrate services by implementing custom applications or workflows that access the full scope of the platform, allowing you to build a powerful experience in Slack.

This is a simpler version of Slack's Giphy. The original Giphy Slack application responds to search requests by responding to multiple GIF. For simplicity, the functional application demonstrated in this article only uses Giphy Random API to return a single (random) image corresponding to the search keyword. This blog post provides a step-by-step guide to deploying an application to Azure Functions and integrating it with a Slack workspace.

In this article, you will:

Learn about custom handlers in Azure Functions

Learn what's going on behind the scenes through a short code exercise.

Learn how to use configuration Azure Functions and Slack to set up the solution

Of course, run your Slack application in the workspace!

The back-end function logic is written in Go (the code can be found on GitHub. Those of you who have used Azure Functions may recall that Go is not one of the language processors supported by default. This is where custom handlers come to the rescue!

What is a custom handler?

In short, a custom handler is a lightweight Web server that receives events from a Functions host. The only thing you need to implement custom handlers in your favorite runtime / language is HTTP support! This does not mean that custom handlers are limited to HTTP triggers-you are free to use other triggers and input and output bindings through the expansion pack.

This is a summary of how custom handlers work at a high level (the following figure is excerpted from the document)

Event triggers (through HTTP, storage, event center, and so on) invoke the Functions host. The way the custom handler differs from the traditional function is that the host of this function acts as the middleman: it has a load along the request to the custom handler (function) Web server load contains triggers, input data binding, and other functions of metadata. This function returns the response to the Functions host, which passes the data from the response to the function's output binding for processing.

Overview

Before we delve deeper into other areas, exploring the code (by the way, relatively simple) may help to understand the essence

Application structure

Let's see how the application is set up. This is defined in the document

Java:

├── cmd │ └── main.go ├── funcy │ └── function.json ├── go.mod ├── host.json └── pkg └── function ├── function.go ├── giphy.go └── slack.go

The function.json file is located in a folder and its name is conventionally used as the function name.

Java:

{"bindings": [{"type": "httpTrigger", "direction": "in", "name": "req", "methods": ["get", "post"]}, {"type": "http" "direction": "out", "name": "res"]}

Host.json tells the Functions host where to send the request by pointing to the Web server that can handle HTTP events. Notice customHandler.description.defaultExecutablePath, which defines the name of the executable that go_funcy will use to run the network server. "enableForwardingHttpRequest": true ensures that the raw HTTP data is sent to the custom handler without any modification.

Java:

{"version": "2. 0", "extensionBundle": {"id": "Microsoft.Azure.Functions.ExtensionBundle", "version": "[1. 0, 2. 0)"}, "customHandler": {"description": {"defaultExecutablePath": "go_funcy"}, "enableForwardingHttpRequest": true} "logging": {"logLevel": {"default": "Trace"}

The cmd and pkg directories contain the go source code. Let's discuss this in the next section.

Code exercise

Cmd/main.go sets up and starts the HTTP server. Note that the / api/funcy endpoint is the endpoint where the Function host sends requests to the custom handler HTTP server.

Java:

Func main () {port, exists: = os.LookupEnv ("FUNCTIONS_CUSTOMHANDLER_PORT") if! exists {port = "8080"} http.HandleFunc ("/ api/funcy", function.Funcy) log.Fatal (http.ListenAndServe (":" + port, nil))}

All the hard work is in function/function.go.

The first part is to read the request body (from Slack) and ensure its integrity through a signature verification process based on the recipe defined by Slack.

Java:

SigningSecret: = os.Getenv ("SLACK_SIGNING_SECRET") apiKey: = os.Getenv ("GIPHY_API_KEY") if signingSecret = = "| | apiKey ="{http.Error (w," Failed to process request.) Please contact the admin ", http.StatusUnauthorized) return} slackTimestamp: = r.Header.Get (" X-Slack-Request-Timestamp ") b, err: = ioutil.ReadAll (r.Body) if err! = nil {http.Error (w," Failed to process request ") Http.StatusBadRequest) return} slackSigningBaseString: = "v0:" + slackTimestamp + ":" + string (b) slackSignature: = r.Header.Get ("X-Slack-Signature") if! matchSignature (slackSignature, signingSecret, slackSigningBaseString) {http.Error (w, "Function was not invoked by Slack", http.StatusForbidden) return}

Once we confirm that the function is indeed called through Slack, the next part is to Slack the search terms entered by the user.

Java:

Vals, err: = parse (b) if err! = nil {http.Error (w, "Failed to process request", http.StatusBadRequest) return;} giphyTag: = vals.Get ("text")

Use the search term to find GIF by calling GIPHY REST API.

Java:

GiphyResp, err: = http.Get ("http://api.giphy.com/v1/gifs/random?tag=" + giphyTag +" & api_key= "+ apiKey) if err! = nil {http.Error (w," Failed to process request ", http.StatusFailedDependency) return} resp, err: = ioutil.ReadAll (giphyResp.Body) if err! = nil {http.Error (w," Failed to process request ", http.StatusInternalServerError) return}

Unmarshal the response sent back by GIPHY API, convert it into a form that Slack can understand, and then return. okay!

Java:

Var gr GiphyResponse json.Unmarshal (resp, & gr) title: = gr.Data.Title url: = gr.Data.Images.Downsized.URL slackResponse: = SlackResponse {Text: slackResponseStaticText, Attachments: [] Attachment {{Text: title, ImageURL: url} w.Header (). Set ("Content-Type", "application/json") json.NewEncoder (w) .Encode (slackResponse) fmt.Println ("Sent response to Slack")

MatchSignature if you are interested in checking the signature verification process, check this function and look at slack.go, giphy.go (in the function directory) to see the Go structure used to represent the information exchanged between components (JSON). In order to keep this article concise, these are not included here.

Well, so far, we have introduced a lot of theory and background information. It's time to get things done! Before continuing, make sure that you meet the prerequisites mentioned below.

precondition

If you don't already have Go, download and install it.

Installing Azure Functions Core Tools administrators will allow you to deploy the function using CLI (and you can also run it locally for testing and debugging).

If not, create a Slack workspace.

Get the GIPHY API key-you need to create a GIHPY account (it's free! And create an application Each application you create has its own API key.

Please copy your GIPHY API key because you will use it later.

The next section guides you through the process of deploying the Azure function and configuring Slack for the Slash command.

Azure function Settings

First create a resource group to host all the components of the solution.

Create a function application

First search for Function App in the Azure portal, and then click add.

Enter the required details: you should select a custom handler as the runtime stack.

In the Hosting section, select Linux and Consumption (Serverless) for the operating system and plan type, respectively.

Enable Application Insights, if required.

Review the final settings and click create to continue.

When the process is complete, the following resources will also be created with Function App:

Application service plan (in this case, consumption / serverless plan).

An Azure storage account.

An Azure application revelation.

Deployment function

Clone the GitHub repository and build the function.

Java:

Git clone https://github.com/abhirockzz/serverless-go-slack-appcd serverless-go-slack-appGOOS=linux go build-o go_funcy cmd/main.go

GOOS=linux is used to build the Linux executable because we Linux chose the operating system for Function App.

To deploy, use the Azure Functions core tool CLI.

Java:

Func azure functionapp publish

After deployment, copy the function URL returned by the command reply, which you will use in the next steps.

Configuration slack

This section describes the steps required to set up the Slack application (Slash command) in the workspace:

Create a Slack application.

Create a slash command.

Install the application into your workspace.

Create Slack applications and Slash commands

Log in to your Slack workspace and start creating a new Slack application.

Click create New Command to define a new slash command with the required information. Note that the request URL field is the field of the HTTP endpoint that you will enter into the function, and it is just the URL you got after you deployed the function in the previous section. When you are finished, click Save finish.

Install the application into your workspace

After you have finished creating the Slash command, go to the application's settings page, click basic Information in the Navigation menu, select install the application to the workspace, and then click install the application to the workspace. This will install the application to your workspace to test your application and generate the Slack workspace for the tokens needed to interact with Slack API. After the application is installed, the application credentials are displayed on the same page.

Make a note of your application signing key because you will use it later. Before you get into the interesting part,

Be sure to update the Function App configuration to add Slack Signing Secret (SLACK_SIGNING_SECRET) and Giphy API key (GIPHY_API_KEY)? they will be available as environment variables within the function.

FUN (cy) time!

We can call the command / funcy from your Slack workspace. For example, try / funcy dog.

You should get back a random GIF in return!

A brief review of what's happening: when you / funcy invokes a command in Slack, it calls the function, then interacts with Giphy API and eventually returns GIF to the user (if all goes well).

You might see timeout error in Slack after the first call. This is probably because cold start the function takes a few seconds to boot the first time it is called. This is combined with the fact that Slack expects a response within 3 seconds to give an error message.

There's nothing to worry about. All you need is to try again and everything will be all right!

Clear

When we finish this test, don't forget to delete the resource group, that is, we will delete all previously created resources (functional applications, application service plans, etc.).

Thank you for reading, the above is the content of "how to use Go and AzureFunctions to build serverless applications". After the study of this article, I believe you have a deeper understanding of how to use Go and AzureFunctions to build serverless applications. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report