-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathchatparam.go
More file actions
50 lines (43 loc) · 1.26 KB
/
chatparam.go
File metadata and controls
50 lines (43 loc) · 1.26 KB
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
package httpmw
import (
"context"
"net/http"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/codersdk"
)
type chatParamContextKey struct{}
// ChatParam returns the chat from the ExtractChatParam handler.
func ChatParam(r *http.Request) database.Chat {
chat, ok := r.Context().Value(chatParamContextKey{}).(database.Chat)
if !ok {
panic("developer error: chat param middleware not provided")
}
return chat
}
// ExtractChatParam grabs a chat from the "chat" URL parameter.
func ExtractChatParam(db database.Store) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()
chatID, parsed := ParseUUIDParam(rw, r, "chat")
if !parsed {
return
}
chat, err := db.GetChatByID(ctx, chatID)
if httpapi.Is404Error(err) {
httpapi.ResourceNotFound(rw)
return
}
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Internal error fetching chat.",
Detail: err.Error(),
})
return
}
ctx = context.WithValue(ctx, chatParamContextKey{}, chat)
next.ServeHTTP(rw, r.WithContext(ctx))
})
}
}