Clerk logo

Clerk Docs

Ctrl + K
Go to clerk.devGet API keys

Handling requests with Go

Go Middleware

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

package main
import (
"net/http"
"github.com/clerkinc/clerk-sdk-go/clerk"
)
func main() {
client, _ := clerk.NewClient("CLERK_API_KEY")
mux := http.NewServeMux()
injectActiveSession := clerk.WithSession(client)
mux.Handle("/hello", injectActiveSession(helloUserHandler(client)))
http.ListenAndServe(":8080", mux)
}
func helloUserHandler(client clerk.Client) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
sessClaims, ok := ctx.Value(clerk.ActiveSessionClaims).(*clerk.SessionClaims)
if !ok {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Unauthorized"))
return
}
user, err := client.Users().Read(sessClaims.Subject)
if err != nil {
panic(err)
}
w.Write([]byte("Welcome " + *user.FirstName))
}
}

Was this helpful?

Clerk © 2022