add point to handle sessions in the admin panel
This commit is contained in:
parent
0980b8d0a6
commit
d3bfe13eba
6
admin.go
6
admin.go
|
@ -8,9 +8,15 @@ import (
|
|||
|
||||
func AdminRoutes(router *httprouter.Router) {
|
||||
p := "/admin/" // prefix
|
||||
router.GET(p + "login", AdminLogin)
|
||||
router.GET(p + "foo", AdminFoo)
|
||||
}
|
||||
|
||||
// Login the user into the admin panel
|
||||
func AdminLogin(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
||||
fmt.Fprint(w, "You now have a valid login!")
|
||||
}
|
||||
|
||||
func AdminFoo(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
|
||||
fmt.Fprintf(w, "Adminpanel not implemented yet!")
|
||||
}
|
||||
|
|
32
main.go
32
main.go
|
@ -8,6 +8,7 @@ import (
|
|||
"log"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
|
@ -21,19 +22,40 @@ type (
|
|||
Connection string // the URL to the database
|
||||
TemplatePath string // path to the templates
|
||||
}
|
||||
Logger struct {
|
||||
Middleware struct {
|
||||
router *httprouter.Router
|
||||
}
|
||||
)
|
||||
|
||||
var (
|
||||
admin_url_prefix = "/admin"
|
||||
)
|
||||
|
||||
// logger works as a middleware here
|
||||
func (l Logger) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
func (l Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
w.Header()["Content-Type"] = []string{"text/html"}
|
||||
l.router.ServeHTTP(w, r)
|
||||
l.session(w, r)
|
||||
log.Print(r.URL.Path, ";", time.Since(start))
|
||||
}
|
||||
|
||||
func (l *Middleware) session(w http.ResponseWriter, r *http.Request) {
|
||||
// catch admin panel sessions
|
||||
if strings.HasPrefix(r.URL.Path, admin_url_prefix) {
|
||||
if !check_valid_session(w, r) { return }
|
||||
}
|
||||
l.router.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
func check_valid_session(w http.ResponseWriter, r *http.Request) bool {
|
||||
if r.URL.Path == "/admin/login" {
|
||||
return true
|
||||
}
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
fmt.Fprint(w, "No session found!")
|
||||
return false
|
||||
}
|
||||
|
||||
func main() {
|
||||
var config_path string
|
||||
flag.StringVar(&config_path, "config", "config.yml", "path to the config file")
|
||||
|
@ -77,6 +99,6 @@ func readConfig(config_path string) (*Config, error) {
|
|||
|
||||
// start the server with access log
|
||||
func start_server(config *Config, router *httprouter.Router) {
|
||||
logger := Logger{router}
|
||||
log.Print(http.ListenAndServe(fmt.Sprintf("%v:%v", config.Address, config.Port), logger))
|
||||
middleware := Middleware{router}
|
||||
log.Print(http.ListenAndServe(fmt.Sprintf("%v:%v", config.Address, config.Port), middleware))
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue