Skip to content

Commit 42405f3

Browse files
committed
New util package created
1 parent ff499ff commit 42405f3

File tree

4 files changed

+85
-75
lines changed

4 files changed

+85
-75
lines changed

cmd/main.go

Lines changed: 53 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ import (
1818
"github.com/rs/cors"
1919
"github.com/rs/zerolog"
2020

21-
"google.golang.org/grpc"
22-
"google.golang.org/grpc/credentials/insecure"
21+
// "google.golang.org/grpc"
22+
// "google.golang.org/grpc/credentials/insecure"
2323
)
2424

2525
const (
@@ -77,55 +77,55 @@ func main() {
7777

7878
// === gRPC Connection to Auth Microservice ==========================
7979

80-
authGrpcAddr := os.Getenv("AUTH_GRPC_SERVER_ADDRESS")
81-
if authGrpcAddr == "" {
82-
authGrpcAddr = "localhost:5001"
83-
pkg.Logger.Warn().Msgf(
84-
"AUTH_GRPC_SERVER_ADDRESS not set, defaulting to %s",
85-
authGrpcAddr,
86-
)
87-
}
88-
89-
var authConn *grpc.ClientConn
90-
91-
for i := range MaxDBRetries {
92-
pkg.Logger.Info().Msgf(
93-
"Attempting to connect to Auth gRPC service at %s (Attempt %d/%d)...",
94-
authGrpcAddr, i+1, MaxDBRetries,
95-
)
96-
97-
// Replaces deprecated grpc.WithTimeout()
98-
ctx, cancel := context.WithTimeout(context.Background(), DBRetryDelay)
99-
defer cancel()
100-
101-
//nolint:staticcheck
102-
conn, err := grpc.DialContext(
103-
ctx,
104-
authGrpcAddr,
105-
grpc.WithTransportCredentials(insecure.NewCredentials()),
106-
grpc.WithBlock(),
107-
)
108-
109-
if err == nil {
110-
authConn = conn
111-
pkg.Logger.Info().Msg("[AUTH]: Auth gRPC service connection successful.")
112-
break
113-
}
114-
115-
pkg.Logger.Warn().Err(err).Msgf(
116-
"Auth gRPC connection failed. Retrying in %s...",
117-
DBRetryDelay,
118-
)
119-
120-
time.Sleep(DBRetryDelay)
121-
}
122-
123-
if authConn == nil {
124-
pkg.Logger.Fatal().Msg("[CRASH]: Failed to connect to Auth gRPC service after multiple retries")
125-
}
126-
defer authConn.Close()
127-
128-
authMiddleware := middleware.NewAuthMiddleware(authConn, logger)
80+
// authGrpcAddr := os.Getenv("AUTH_GRPC_SERVER_ADDRESS")
81+
// if authGrpcAddr == "" {
82+
// authGrpcAddr = "localhost:5001"
83+
// pkg.Logger.Warn().Msgf(
84+
// "AUTH_GRPC_SERVER_ADDRESS not set, defaulting to %s",
85+
// authGrpcAddr,
86+
// )
87+
// }
88+
89+
// var authConn *grpc.ClientConn
90+
91+
// for i := range MaxDBRetries {
92+
// pkg.Logger.Info().Msgf(
93+
// "Attempting to connect to Auth gRPC service at %s (Attempt %d/%d)...",
94+
// authGrpcAddr, i+1, MaxDBRetries,
95+
// )
96+
97+
// // Replaces deprecated grpc.WithTimeout()
98+
// ctx, cancel := context.WithTimeout(context.Background(), DBRetryDelay)
99+
// defer cancel()
100+
101+
// //nolint:staticcheck
102+
// conn, err := grpc.DialContext(
103+
// ctx,
104+
// authGrpcAddr,
105+
// grpc.WithTransportCredentials(insecure.NewCredentials()),
106+
// grpc.WithBlock(),
107+
// )
108+
109+
// if err == nil {
110+
// authConn = conn
111+
// pkg.Logger.Info().Msg("[AUTH]: Auth gRPC service connection successful.")
112+
// break
113+
// }
114+
115+
// pkg.Logger.Warn().Err(err).Msgf(
116+
// "Auth gRPC connection failed. Retrying in %s...",
117+
// DBRetryDelay,
118+
// )
119+
120+
// time.Sleep(DBRetryDelay)
121+
// }
122+
123+
// if authConn == nil {
124+
// pkg.Logger.Fatal().Msg("[CRASH]: Failed to connect to Auth gRPC service after multiple retries")
125+
// }
126+
// defer authConn.Close()
127+
128+
// authMiddleware := middleware.NewAuthMiddleware(authConn, logger)
129129

130130
// === Jupyter Gateway Initialization =================================
131131

@@ -145,8 +145,8 @@ func main() {
145145
// === HTTP Server =====================================================
146146

147147
mux := http.NewServeMux()
148-
routes.RegisterAPIRoutes(mux, jupyterGateway, authMiddleware)
149-
148+
// routes.RegisterAPIRoutes(mux, jupyterGateway, authMiddleware)
149+
routes.RegisterAPIRoutes(mux, jupyterGateway)
150150
loggedMux := middleware.RequestLogger(mux)
151151

152152
corsHandler := cors.New(cors.Options{

controllers/notebook_controller.go

Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
package controllers
22

33
import (
4-
"context"
4+
"time"
55
"encoding/json"
6+
"context"
67
"fmt"
78
"net/http"
8-
"time"
99

1010
"github.com/Thanus-Kumaar/controller_microservice_v2/modules"
1111
"github.com/Thanus-Kumaar/controller_microservice_v2/pkg/models"
12+
"github.com/Thanus-Kumaar/controller_microservice_v2/pkg" // Added pkg import
1213
"github.com/rs/zerolog"
1314
)
1415

@@ -25,16 +26,7 @@ func NewNotebookController(module *modules.NotebookModule, logger *zerolog.Logge
2526
}
2627
}
2728

28-
// helper
29-
func writeJSONResponseWithLogger(w http.ResponseWriter, status int, v any, logger *zerolog.Logger) {
30-
w.Header().Set("Content-Type", "application/json")
31-
w.WriteHeader(status)
32-
if v != nil {
33-
if err := json.NewEncoder(w).Encode(v); err != nil {
34-
logger.Error().Err(err).Msg("failed to encode response")
35-
}
36-
}
37-
}
29+
3830

3931
// CreateNotebookHandler handles POST /api/v1/notebooks
4032
func (c *NotebookController) CreateNotebookHandler(w http.ResponseWriter, r *http.Request) {
@@ -52,7 +44,7 @@ func (c *NotebookController) CreateNotebookHandler(w http.ResponseWriter, r *htt
5244
http.Error(w, fmt.Sprintf("error creating notebook: %v", err), http.StatusInternalServerError)
5345
return
5446
}
55-
writeJSONResponseWithLogger(w, http.StatusCreated, nb, c.Logger)
47+
pkg.WriteJSONResponseWithLogger(w, http.StatusCreated, nb, c.Logger)
5648
}
5749

5850
// ListNotebooksHandler handles GET /api/v1/notebooks
@@ -67,7 +59,7 @@ func (c *NotebookController) ListNotebooksHandler(w http.ResponseWriter, r *http
6759
http.Error(w, "error listing notebooks", http.StatusInternalServerError)
6860
return
6961
}
70-
writeJSONResponseWithLogger(w, http.StatusOK, nbs, c.Logger)
62+
pkg.WriteJSONResponseWithLogger(w, http.StatusOK, nbs, c.Logger)
7163
}
7264

7365
// GetNotebookByIDHandler handles GET /api/v1/notebooks/{id}
@@ -82,7 +74,7 @@ func (c *NotebookController) GetNotebookByIDHandler(w http.ResponseWriter, r *ht
8274
http.Error(w, "not found", http.StatusNotFound)
8375
return
8476
}
85-
writeJSONResponseWithLogger(w, http.StatusOK, nb, c.Logger)
77+
pkg.WriteJSONResponseWithLogger(w, http.StatusOK, nb, c.Logger)
8678
}
8779

8880
// UpdateNotebookByIDHandler handles PUT /api/v1/notebooks/{id}
@@ -102,7 +94,7 @@ func (c *NotebookController) UpdateNotebookByIDHandler(w http.ResponseWriter, r
10294
http.Error(w, "error updating notebook", http.StatusInternalServerError)
10395
return
10496
}
105-
writeJSONResponseWithLogger(w, http.StatusOK, updated, c.Logger)
97+
pkg.WriteJSONResponseWithLogger(w, http.StatusOK, updated, c.Logger)
10698
}
10799

108100
// DeleteNotebookByIDHandler handles DELETE /api/v1/notebooks/{id}
@@ -116,5 +108,5 @@ func (c *NotebookController) DeleteNotebookByIDHandler(w http.ResponseWriter, r
116108
http.Error(w, "error deleting notebook", http.StatusInternalServerError)
117109
return
118110
}
119-
writeJSONResponseWithLogger(w, http.StatusNoContent, nil, c.Logger)
111+
pkg.WriteJSONResponseWithLogger(w, http.StatusNoContent, nil, c.Logger)
120112
}

controllers/problem_controller.go

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"time"
1010

1111
"github.com/Thanus-Kumaar/controller_microservice_v2/modules"
12+
"github.com/Thanus-Kumaar/controller_microservice_v2/pkg"
1213
"github.com/Thanus-Kumaar/controller_microservice_v2/pkg/models"
1314
"github.com/rs/zerolog"
1415
)
@@ -36,7 +37,7 @@ func (c *ProblemController) CreateProblemHandler(w http.ResponseWriter, r *http.
3637
const hardcodedUserID = "123e4567-e89b-12d3-a456-426614174000"
3738

3839
var req models.CreateProblemRequest
39-
if err:= json.NewDecoder(r.Body).Decode(&req); err!=nil {
40+
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
4041
http.Error(w, "invalid request body", http.StatusBadRequest)
4142
return
4243
}
@@ -46,7 +47,7 @@ func (c *ProblemController) CreateProblemHandler(w http.ResponseWriter, r *http.
4647
http.Error(w, fmt.Sprintf("error creating problem statemnet: %v", err), http.StatusInternalServerError)
4748
return
4849
}
49-
writeJSONResponseWithLogger(w, http.StatusCreated, problemStatement, &c.Logger)
50+
pkg.WriteJSONResponseWithLogger(w, http.StatusCreated, problemStatement, &c.Logger)
5051
}
5152

5253
// ListProblemsHandler handles GET /api/v1/problems
@@ -65,7 +66,7 @@ func (c *ProblemController) ListProblemsHandler(w http.ResponseWriter, r *http.R
6566
}
6667

6768
// If no problems are found, it should return an empty list, not an error.
68-
writeJSONResponseWithLogger(w, http.StatusOK, problems, &c.Logger)
69+
pkg.WriteJSONResponseWithLogger(w, http.StatusOK, problems, &c.Logger)
6970
}
7071

7172
// GetProblemByIDHandler handles GET /api/v1/problems/{id}
@@ -85,7 +86,7 @@ func (c *ProblemController) GetProblemByIDHandler(w http.ResponseWriter, r *http
8586
return
8687
}
8788

88-
writeJSONResponseWithLogger(w, http.StatusOK, problem, &c.Logger)
89+
pkg.WriteJSONResponseWithLogger(w, http.StatusOK, problem, &c.Logger)
8990
}
9091

9192
// UpdateProblemByIDHandler handles PUT /api/v1/problems/{id}
@@ -112,7 +113,7 @@ func (c *ProblemController) UpdateProblemByIDHandler(w http.ResponseWriter, r *h
112113
return
113114
}
114115

115-
writeJSONResponseWithLogger(w, http.StatusOK, updatedProblem, &c.Logger)
116+
pkg.WriteJSONResponseWithLogger(w, http.StatusOK, updatedProblem, &c.Logger)
116117
}
117118

118119
// DeleteProblemByIDHandler handles DELETE /api/v1/problems/{id}

pkg/http_utils.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package pkg
2+
3+
import (
4+
"encoding/json"
5+
"net/http"
6+
7+
"github.com/rs/zerolog"
8+
)
9+
10+
// WriteJSONResponseWithLogger is a helper function to write JSON responses with logging.
11+
func WriteJSONResponseWithLogger(w http.ResponseWriter, status int, data interface{}, logger *zerolog.Logger) {
12+
w.Header().Set("Content-Type", "application/json")
13+
w.WriteHeader(status)
14+
if err := json.NewEncoder(w).Encode(data); err != nil {
15+
logger.Error().Err(err).Msg("failed to write json response")
16+
}
17+
}

0 commit comments

Comments
 (0)