Brijesh's Git Server — argus-core @ 7fe70b23373de45a57bafd87ca06a5688da4c3f6

Logging service

internal/server/server.go (view raw)

 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
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
package server

import (
	"fmt"
	"net/http"
	"os"
	"strconv"
	"time"

	_ "github.com/joho/godotenv/autoload"

	"argus-core/internal/applications"
	"argus-core/internal/auth"
	"argus-core/internal/database"
	applicationspb "argus-core/rpc/applications"
	authpb "argus-core/rpc/auth"
)

type Server struct {
	port int
	db   database.Service
	auth auth.Service
}

// CORSMiddleware wraps a handler with CORS support
func CORSMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Set CORS headers
		w.Header().Set("Access-Control-Allow-Origin", "*") // In production, replace * with your frontend domain
		w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
		w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, Authorization")

		// Handle preflight requests
		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusOK)
			return
		}

		// Call the next handler
		next.ServeHTTP(w, r)
	})
}

func NewServer() *http.Server {
	port, _ := strconv.Atoi(os.Getenv("PORT"))

	// Initialize database service
	db := database.New()

	// Initialize auth service
	authService := auth.NewService(db, auth.Config{
		JWTSecret:     os.Getenv("JWT_SECRET"),
		TokenDuration: 24 * time.Hour,
	})

	// Create Twirp Server handlers
	authHandler := authpb.NewAuthServiceServer(auth.NewTwirpServer(authService))
	applicationsHandler := applicationspb.NewApplicationsServiceServer(applications.NewTwirpServer(authService, db))

	// Combine handlers
	mux := http.NewServeMux()
	mux.Handle(authHandler.PathPrefix(), authHandler)
	mux.Handle(applicationsHandler.PathPrefix(), applicationsHandler)

	// Wrap the mux with CORS middleware
	handler := CORSMiddleware(mux)

	// Declare Server config
	server := &http.Server{
		Addr:         fmt.Sprintf(":%d", port),
		Handler:      handler,
		IdleTimeout:  time.Minute,
		ReadTimeout:  10 * time.Second,
		WriteTimeout: 30 * time.Second,
	}

	return server
}