Mode:
Duration:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package main
import (
"fmt"
"net/http"
)
func authorize(requiredRole string, next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
userRole := r.Header.Get("Role")
if userRole != requiredRole {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
next(w, r)
}
}
func adminHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Welcome, Admin!")
}
func main() {
http.HandleFunc("/admin", authorize("admin", adminHandler))
fmt.Println("Server running at http://localhost:8080")
http.ListenAndServe(":8080", nil)
}Coding works best on desktop or with an external keyboard.