Handling requests with Go

Go Middleware

The Clerk Go SDK provides a simple middleware that adds the active session to the request’s context.

.env
1
package main
2
3
import (
4
"net/http"
5
"github.com/clerkinc/clerk-sdk-go/clerk"
6
)
7
8
func main() {
9
client, _ := clerk.NewClient(your_secret_key)
10
11
mux := http.NewServeMux()
12
13
injectActiveSession := clerk.WithSession(client)
14
mux.Handle("/hello", injectActiveSession(helloUserHandler(client)))
15
16
http.ListenAndServe(":8080", mux)
17
}
18
19
func helloUserHandler(client clerk.Client) http.HandlerFunc {
20
return func(w http.ResponseWriter, r *http.Request) {
21
ctx := r.Context()
22
23
sessClaims, ok := ctx.Value(clerk.ActiveSessionClaims).(*clerk.SessionClaims)
24
if !ok {
25
w.WriteHeader(http.StatusUnauthorized)
26
w.Write([]byte("Unauthorized"))
27
return
28
}
29
30
user, err := client.Users().Read(sessClaims.Subject)
31
if err != nil {
32
panic(err)
33
}
34
35
w.Write([]byte("Welcome " + *user.FirstName))
36
}
37
}

Was this helpful?

Clerk © 2025