12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- package snap
- import (
- "fmt"
- "net/http"
- "git.thirdmartini.com/pub/snap/auth"
- )
- type RouteBuilder struct {
- auth auth.Authenticator
- contentHandler func(c *Context)
- loginHandler func(c *Context) bool
- }
- func (r *RouteBuilder) WithLoginHandler(loginHandler func(c *Context) bool) *RouteBuilder {
- return &RouteBuilder{
- auth: r.auth,
- loginHandler: loginHandler,
- contentHandler: r.contentHandler,
- }
- return r
- }
- func (r *RouteBuilder) WithAuth(auth auth.Authenticator) *RouteBuilder {
- return &RouteBuilder{
- auth: auth,
- loginHandler: r.loginHandler,
- contentHandler: r.contentHandler,
- }
- }
- func (r *RouteBuilder) WithContent(contentHandler func(c *Context)) *RouteBuilder {
- return &RouteBuilder{
- auth: r.auth,
- loginHandler: r.loginHandler,
- contentHandler: contentHandler,
- }
- }
- func (r *RouteBuilder) BuildRoute(s *Server) http.HandlerFunc {
- if r.auth == nil {
- return func(w http.ResponseWriter, req *http.Request) {
- c := s.makeContext(nil, w, req)
- r.contentHandler(c)
- }
- }
- return func(w http.ResponseWriter, req *http.Request) {
- rec, ok := r.auth.DoAuth(w, req)
- if !ok {
- if r.loginHandler != nil {
- c := s.makeContext(rec, w, req)
- if r.loginHandler(c) == false {
- return
- }
- }
- fmt.Printf("Sending to: %s\n", req.URL.Path)
- req.Method = http.MethodGet
- http.Redirect(w, req, req.URL.Path, http.StatusSeeOther)
- return
- }
- c := s.makeContext(rec, w, req)
- r.contentHandler(c)
- }
- }
- func NewRouteBuilder() *RouteBuilder {
- return &RouteBuilder{}
- }
|