Chapter 03 of 8
Where the REST API is defined and how the Gateway routes requests to internal handlers.
The OpenFaaS REST API is defined in the Gateway's HTTP server setup, using Go's standard HTTP package and custom routing logic to handle different types of requests.
main.go
handlers/ package
middleware/ package
The OpenFaaS API follows RESTful principles and is organized into logical groups based on functionality.
The Gateway uses a sophisticated routing system that matches incoming HTTP requests to the appropriate handler functions based on URL patterns and HTTP methods.
HTTP request reaches the Gateway server
Request URL is parsed to extract path and query parameters
URL pattern is matched against registered routes
Appropriate handler function is selected
Handler processes the request and generates response
Here's how the API routes are defined in the OpenFaaS Gateway codebase.
func setupRoutes(router *mux.Router, h *handlers.Handler) { // Function management routes router.HandleFunc("/system/functions", h.ListFunctions).Methods("GET") router.HandleFunc("/system/functions", h.DeployFunction).Methods("POST") router.HandleFunc("/system/functions/{name}", h.DeleteFunction).Methods("DELETE") // Function invocation routes router.HandleFunc("/function/{name}", h.InvokeFunction).Methods("POST", "GET", "PUT", "DELETE") // System routes router.HandleFunc("/system/info", h.SystemInfo).Methods("GET") router.HandleFunc("/healthz", h.Health).Methods("GET")}
The API routes are enhanced with middleware that provides cross-cutting concerns like authentication, logging, and request validation.
Validates API keys, JWT tokens, or other authentication mechanisms before processing requests.
Logs incoming requests, response times, and error conditions for monitoring and debugging.
Handles Cross-Origin Resource Sharing headers for web-based clients.
Prevents abuse by limiting the number of requests from a single client.
Now that you understand how the API is defined and routes requests, let's explore how the Gateway transforms and authenticates requests through middleware.