go-captiveportal/middleware.go

53 lines
942 B
Go
Raw Normal View History

2020-10-16 17:27:44 +02:00
package captiveportal
import (
"net/http"
"github.com/pkg/errors"
)
func (s *Service) Middleware() func(next http.Handler) http.Handler {
registry := s.registry
matcher := s.options.Matcher
liar := s.options.Liar
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
matches, os, err := matcher.Match(r)
if err != nil {
panic(errors.WithStack(err))
}
if !matches {
next.ServeHTTP(w, r)
return
}
id, err := s.options.Identifier.Identify(r)
if err != nil {
panic(errors.Wrap(err, ErrClientIdentificationFailed.Error()))
}
registry.Touch(id, os)
if registry.IsLying(id) {
liar.Handle(os, w, r)
return
}
if registry.IsCaptive(id) {
// Redirect to configured URL
http.Redirect(w, r, s.captivePortalURL, http.StatusTemporaryRedirect)
return
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}