1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
package main
import (
"log"
"net/http"
"time"
)
type App struct {
Store
}
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 (app *App) loginHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
if err := r.ParseForm(); err != nil {
panic(err)
} else {
username := r.Form.Get("username")
password := r.Form.Get("password")
row := app.Query("SELECT id FROM users WHERE user_name = ?", username)
var id int64
if err := row.rowScan(&id); err != nil {
panic(err)
}
}
}
}
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)
}
}
|