forked from dunglas/mercure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo.go
49 lines (42 loc) · 1.38 KB
/
demo.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
package mercure
import (
"fmt"
"io"
"mime"
"net/http"
"path/filepath"
"time"
)
// Demo exposes INSECURE Demo endpoints to test discovery and authorization mechanisms.
// Add a query parameter named "body" to define the content to return in the response's body.
// Add a query parameter named "jwt" set a "mercureAuthorization" cookie containing this token.
// The Content-Type header will automatically be set according to the URL's extension.
func Demo(w http.ResponseWriter, r *http.Request) {
// JSON-LD is the preferred format
mime.AddExtensionType(".jsonld", "application/ld+json")
url := r.URL.String()
mimeType := mime.TypeByExtension(filepath.Ext(r.URL.Path))
query := r.URL.Query()
body := query.Get("body")
jwt := query.Get("jwt")
header := w.Header()
// Several Link headers are set on purpose to allow testing advanced discovery mechanism
header.Add("Link", "<"+defaultHubURL+">; rel=\"mercure\"")
header.Add("Link", fmt.Sprintf("<%s>; rel=\"self\"", url))
if mimeType != "" {
header.Set("Content-Type", mimeType)
}
cookie := &http.Cookie{
Name: "mercureAuthorization",
Path: defaultHubURL,
Value: jwt,
HttpOnly: r.TLS != nil,
SameSite: http.SameSiteStrictMode,
}
if jwt == "" {
// Remove cookie if not provided, to be sure a previous one doesn't exist
cookie.Expires = time.Unix(0, 0)
}
http.SetCookie(w, cookie)
io.WriteString(w, body)
}