Files
gotsrpc/example/auth/main.go
Uwe Quitter 5d68c02535 feat: Add authentication example demonstrating gotsrpc Context function
This example showcases gotsrpc's special Context function for centralized
authentication. The Context function handles all authentication logic,
keeping service methods clean and focused on business logic.

Key principle: Centralized authentication via Context function
- Context function validates Authorization header once
- Service methods remain clean without auth boilerplate
- Single point of authentication for entire service

Example includes:
- AuthService: Login/logout operations
- HelloService: Demonstrates Context function pattern
- Complete build system with Makefile
- TypeScript client with proper ES6 modules
- Comprehensive tests and documentation

Files: example/auth/ (complete authentication example)
2025-10-22 16:07:17 +02:00

45 lines
1.5 KiB
Go

package main
import (
"fmt"
"log"
"net/http"
"github.com/foomo/gotsrpc/v2/example/auth/service"
)
func main() {
// Create authentication service
authHandler := service.NewAuthHandler()
// Create hello service with authentication dependency
helloHandler := service.NewHelloHandler(authHandler)
// Create gotsrpc proxies using generated code
authProxy := service.NewDefaultAuthServiceGoTSRPCProxy(authHandler)
helloProxy := service.NewDefaultHelloServiceGoTSRPCProxy(helloHandler)
// Create a custom mux to handle routing properly
mux := http.NewServeMux()
// Register gotsrpc handlers first (more specific paths)
mux.Handle("/auth/", authProxy)
mux.Handle("/hello/", helloProxy)
// Serve static files for the client (catch-all for non-API paths)
// This will only match if the above handlers don't match
mux.Handle("/", http.FileServer(http.Dir("./client/")))
fmt.Println("Auth example server starting on :8080")
fmt.Println("Available endpoints:")
fmt.Println(" POST /auth/Login - Login with username/password")
fmt.Println(" POST /auth/Logout - Logout with token")
fmt.Println(" POST /auth/ValidateToken - Validate token")
fmt.Println(" POST /hello/Context - Authentication context (special gotsrpc function)")
fmt.Println(" POST /hello/SayHello - Say hello (requires authentication)")
fmt.Println(" POST /hello/GetUserInfo - Get user info (requires authentication)")
fmt.Println(" GET / - Serve client application")
log.Fatal(http.ListenAndServe(":8080", mux))
}