Skip to content

Instantly share code, notes, and snippets.

@Tanmay451
Last active December 11, 2023 11:39
Show Gist options
  • Save Tanmay451/dda78d29c995821c22542b1008f97fd5 to your computer and use it in GitHub Desktop.
Save Tanmay451/dda78d29c995821c22542b1008f97fd5 to your computer and use it in GitHub Desktop.
Decorator pattern in Go (golang)
/*
The provided Go code demonstrates the use of a decorator pattern to implement authorization checks for HTTP endpoints. The main components of the code include:
isAuthorized Function:
It takes an HTTP handler function (endpoint) as a parameter and returns an http.Handler.
The returned http.Handler is a function that checks for the presence of an "Authorized" header in the incoming HTTP request.
If the header is present and set to "true," the original endpoint function is called, allowing the request to proceed.
If the header is not present or set to a value other than "true," a "Not Authorized" message is sent as the response.
homePage Function:
This is a sample HTTP handler function representing the home page.
It simply prints a message to the console and sends a "Welcome to the HomePage!" response to the client.
handleRequests Function:
It sets up the routing for the application.
The "/" route is associated with the isAuthorized decorator applied to the homePage function.
The server is started on port 8081, and any incoming requests are processed.
main Function:
It is the entry point of the program, calling the handleRequests function to start the HTTP server.
In summary, this code uses a decorator (isAuthorized) to add an authorization check to the homePage endpoint. The authorization is based on the presence of a specific header in the incoming HTTP request. If the header is valid, the original endpoint is executed; otherwise, a "Not Authorized" message is returned. The code showcases a simple way to implement middleware functionality for HTTP handlers in Go.
*/
package main
import (
"fmt"
"log"
"net/http"
)
func isAuthorized(endpoint func(http.ResponseWriter, *http.Request)) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("Checking to see if Authorized header set...")
if val, ok := r.Header["Authorized"]; ok {
fmt.Println(val)
if val[0] == "true" {
fmt.Println("Header is set! We can serve content!")
endpoint(w, r)
}
} else {
fmt.Println("Not Authorized!!")
fmt.Fprintf(w, "Not Authorized!!")
}
})
}
func homePage(w http.ResponseWriter, r *http.Request) {
fmt.Println("Endpoint Hit: homePage")
fmt.Fprintf(w, "Welcome to the HomePage!")
}
func handleRequests() {
http.Handle("/", isAuthorized(homePage))
log.Fatal(http.ListenAndServe(":8081", nil))
}
func main() {
handleRequests()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment