Add authentication middleware to HTTP handlers
This commit is contained in:
parent
5d6bbdb943
commit
c504f8c597
2 changed files with 37 additions and 4 deletions
31
auth/auth.go
Normal file
31
auth/auth.go
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type Authenticator struct {
|
||||
}
|
||||
|
||||
func (a *Authenticator) Authenticate(in http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
c := http.Cookie{
|
||||
Name: "RequestCounter",
|
||||
}
|
||||
cookie, err := r.Cookie("RequestCounter")
|
||||
if err != nil {
|
||||
cookie = &http.Cookie{
|
||||
Value: "0",
|
||||
}
|
||||
}
|
||||
count, err := strconv.Atoi(cookie.Value)
|
||||
if err != nil {
|
||||
c.Value = "1"
|
||||
} else {
|
||||
c.Value = strconv.Itoa(count + 1)
|
||||
}
|
||||
http.SetCookie(w, &c)
|
||||
in(w, r)
|
||||
}
|
||||
}
|
||||
10
main.go
10
main.go
|
|
@ -5,12 +5,14 @@ import (
|
|||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/Bronku/iroon/auth"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var err error
|
||||
var h handler
|
||||
var a auth.Authenticator
|
||||
defer h.close()
|
||||
|
||||
h.tmpl, err = template.ParseFiles("index.html", "order.html")
|
||||
|
|
@ -23,8 +25,8 @@ func main() {
|
|||
log.Fatal("can't open the databse", err)
|
||||
}
|
||||
|
||||
http.HandleFunc("GET /order/", logger(h.form))
|
||||
http.HandleFunc("GET /", logger(h.index))
|
||||
http.HandleFunc("POST /", logger(h.addOrder))
|
||||
go http.ListenAndServe(":8080", nil)
|
||||
http.HandleFunc("GET /order/", logger(a.Authenticate(h.form)))
|
||||
http.HandleFunc("GET /", logger(a.Authenticate(h.index)))
|
||||
http.HandleFunc("POST /", logger(a.Authenticate(h.addOrder)))
|
||||
http.ListenAndServe(":8080", nil)
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue