forked from go-cas/cas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
127 lines (102 loc) · 2.09 KB
/
example_test.go
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package cas
import (
"bytes"
"flag"
"fmt"
"html/template"
"net/http"
"net/url"
"github.com/golang/glog"
)
type myHandler struct{}
var MyHandler = &myHandler{}
var casURL string
func init() {
flag.StringVar(&casURL, "url", "", "CAS server URL")
}
func main() {
Example()
}
func Example() {
flag.Parse()
if casURL == "" {
flag.Usage()
return
}
glog.Info("Starting up")
m := http.NewServeMux()
m.Handle("/", MyHandler)
url, _ := url.Parse(casURL)
client := NewClient(&Options{
URL: url,
})
server := &http.Server{
Addr: ":8080",
Handler: client.Handle(m),
}
if err := server.ListenAndServe(); err != nil {
glog.Infof("Error from HTTP Server: %v", err)
}
glog.Info("Shutting down")
}
type templateBinding struct {
Username string
Attributes UserAttributes
}
func (h *myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !IsAuthenticated(r) {
RedirectToLogin(w, r)
return
}
if r.URL.Path == "/logout" {
RedirectToLogout(w, r)
return
}
w.Header().Add("Content-Type", "text/html")
tmpl, err := template.New("index.html").Parse(indexHTML)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, error500, err)
return
}
binding := &templateBinding{
Username: Username(r),
Attributes: Attributes(r),
}
html := new(bytes.Buffer)
if err := tmpl.Execute(html, binding); err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, error500, err)
return
}
html.WriteTo(w)
}
const indexHTML = `<!DOCTYPE html>
<html>
<head>
<title>Welcome {{.Username}}</title>
</head>
<body>
<h1>Welcome {{.Username}} <a href="/logout">Logout</a></h1>
<p>Your attributes are:</p>
<ul>{{range $key, $values := .Attributes}}
<li>{{$len := len $values}}{{$key}}:{{if gt $len 1}}
<ul>{{range $values}}
<li>{{.}}</li>{{end}}
</ul>
{{else}} {{index $values 0}}{{end}}</li>{{end}}
</ul>
</body>
</html>
`
const error500 = `<!DOCTYPE html>
<html>
<head>
<title>Error 500</title>
</head>
<body>
<h1>Error 500</h1>
<p>%v</p>
</body>
</html>
`