Skip to content

Instantly share code, notes, and snippets.

@CallumVass
Last active October 14, 2023 18:42
Show Gist options
  • Save CallumVass/a5fe6cc7b558367641afee83338882e9 to your computer and use it in GitHub Desktop.
Save CallumVass/a5fe6cc7b558367641afee83338882e9 to your computer and use it in GitHub Desktop.
Go - Function vs Method
package main
import (
"context"
"net/http"
"github.com/alexedwards/scs/v2"
)
type application struct {
sessionManager *scs.SessionManager
}
// Function as doesn't have any other dependency
func secureHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Security-Policy",
"default-src 'self'; style-src 'self' fonts.googleapis.com; font-src fonts.gstatic.com")
w.Header().Set("Referrer-Policy", "origin-when-cross-origin")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "deny")
w.Header().Set("X-XSS-Protection", "0")
next.ServeHTTP(w, r)
})
}
// Method as it has a 'dependency' (that's how I see it) on my application struct
func (app *application) requireAuthentication(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
profile := app.sessionManager.Get(r.Context(), "profile")
if profile == nil {
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
w.Header().Add("Cache-Control", "no-store")
next.ServeHTTP(w, r)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment