diff options
| -rw-r--r-- | main.go | 46 | ||||
| -rw-r--r-- | store.go | 35 |
2 files changed, 81 insertions, 0 deletions
@@ -0,0 +1,46 @@ +package main + +import ( + "log" + "net/http" + "time" +) + +type App struct { + SessionStore +} + +func logMux(handler http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t := time.Now() + handler.ServeHTTP(w, r) + log.Println(r.Method, r.URL.Path, time.Since(t)) + }) +} + +func (app *App) rootHandler(w http.ResponseWriter, r *http.Request) { + c, err := r.Cookie("id") + //log.Println(r.Header.Get("X-Original-URI")) + //log.Println(r.Host) + if err != nil { + w.WriteHeader(http.StatusUnauthorized) + } else { + if s, ok := app.Get(c.Value); ok { + w.Header().Set("X-Remote-User", s.UserId) + w.WriteHeader(http.StatusOK) + } else { + log.Println("Session does not exist:", c.Value) + w.WriteHeader(http.StatusForbidden) + } + } +} + +func main() { + //log.SetFlags(log.LstdFlags) + store := NewPgStore() + app := &App{store} + http.HandleFunc("/", app.rootHandler) + if err := http.ListenAndServe(":8080", logMux(http.DefaultServeMux)); err != nil { + panic(err) + } +} diff --git a/store.go b/store.go new file mode 100644 index 0000000..b744d88 --- /dev/null +++ b/store.go @@ -0,0 +1,35 @@ +package main + +import ( + "database/sql" + "log" + + _ "github.com/lib/pq" +) + +type Session struct { + Id string + UserId string +} + +type SessionStore interface { + Get(id string) (*Session, bool) +} + +type PgSessionStore struct { + *sql.DB + cache map[string]*Session +} + +func NewPgStore() *PgSessionStore { + db, err := sql.Open("postgres", "postgres://auth_master:pass@localhost/authdb") + if err != nil { + log.Panic(err) + } + return &PgSessionStore{db, make(map[string]*Session)} +} + +func (store *PgSessionStore) Get(id string) (*Session, bool) { + s, ok := store.cache[id] + return s, ok +} |
