New module: Build Serverless apps with Azure and Go
Published Aug 18 2021 01:53 PM 6,691 Views
Microsoft

Serverless architecture is a type of application development that allows you to run logic in the cloud without having to worry about building server infrastructure. Azure Functions implements a serverless architecture that runs your code on demand without requiring you to manually provision servers.

 

To author Azure Functions in Go or Rust, for example, you use a feature called custom handlers. Custom handlers allow you to bring almost any language to Azure Functions.

 

What are custom handlers?

At its core, a custom handler is a web server. The web server receives events from the Functions host. You then have an opportunity to write code in your preferred language to respond to the events.

With custom handlers, you can use any language that supports HTTP primitives. That's nearly any language.

 

An Azure Function app using Go

 

To create such an app, you only need to listen to HTTP events + make some minor configurations. Here's an example of what the code looks like:

 

 

package main

import (
 "fmt"
 "io/ioutil"
 "log"
 "net/http"
 "os"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
  w.Header().Set("Content-Type", "application/json")
  if r.Method == "GET" {
    w.Write([]byte("hello world"))
  } else {
    body, _ := ioutil.ReadAll(r.Body)
    w.Write(body)
  }
}

func main() {
  customHandlerPort, exists := os.LookupEnv("FUNCTIONS_CUSTOMHANDLER_PORT")
  if !exists {
    customHandlerPort = "8080"
  }
  mux := http.NewServeMux()
  // mux.HandleFunc("/api/hello", helloHandler)
  fmt.Println("Go server Listening on: ", customHandlerPort)
  log.Fatal(http.ListenAndServe(":"+customHandlerPort, mux))
}

 

 

To learn more about how to configure the app properly and work with things like message queues, have a look at this module

Build serverless apps with Go and custom handlers - Learn | Microsoft Docs

 

Co-Authors
Version history
Last update:
‎Dec 03 2021 10:53 AM
Updated by: