Skip to content

Commit

Permalink
fix: add logger
Browse files Browse the repository at this point in the history
  • Loading branch information
rohan-b-84 committed Jun 27, 2024
1 parent 24b0033 commit dd8672c
Showing 1 changed file with 33 additions and 2 deletions.
35 changes: 33 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"regexp"
Expand Down Expand Up @@ -48,6 +49,25 @@ type OtpResponse struct {
Timestamp int `json:"timestamp"`
}

type responseRecorder struct {
http.ResponseWriter
status int
size int
}

func (r *responseRecorder) WriteHeader(statusCode int) {
r.status = statusCode
r.ResponseWriter.WriteHeader(statusCode)
}

func LoggerMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
recorder := &responseRecorder{w, http.StatusOK, 0}
next.ServeHTTP(recorder, r)
log.Printf("INFO:\t%s - %q %s %d %s\n", r.RemoteAddr, r.Method, r.RequestURI, recorder.status, http.StatusText(recorder.status))
})
}

func getJwtKey() (string, error) {
jwtKey := os.Getenv("JWT_SECRET_KEY")

Expand Down Expand Up @@ -293,6 +313,9 @@ func handleVerifyOtp(res http.ResponseWriter, req *http.Request) {
}

http.SetCookie(res, &cookie)
res.WriteHeader(http.StatusOK)
res.Header().Set("Content-Type", "text/plain")
res.Write([]byte("OTP Verified Successfully"))
}

func handleValidateJwt(res http.ResponseWriter, req *http.Request) {
Expand All @@ -316,6 +339,9 @@ func handleValidateJwt(res http.ResponseWriter, req *http.Request) {
http.Error(res, ErrJwtTokenExpired.Error(), http.StatusUnauthorized)
return
}

http.Error(res, err.Error(), http.StatusInternalServerError)
return
}

if !token.Valid {
Expand All @@ -336,15 +362,20 @@ func handleValidateJwt(res http.ResponseWriter, req *http.Request) {
}

res.Header().Set("Content-Type", "application/json")
res.WriteHeader(http.StatusOK)
res.Write(claimsJSON)
res.Header().Set("Content-Type", "text/plain")
res.Write([]byte("User JWT was verified"))

}

func main() {
godotenv.Load()

initMailer()

generalCors := cors.New(cors.Options{
AllowedOrigins: []string{"http://localhost:5173", "https://heimdall.metakgp.org"},
AllowedOrigins: []string{"http://localhost", "https://heimdall.metakgp.org"},
AllowCredentials: true,
})

Expand All @@ -359,7 +390,7 @@ func main() {
handler := cors.AllowAll().Handler(mux)

fmt.Println("Heimdall Server running on port : 3333")
err := http.ListenAndServe(":3333", handler)
err := http.ListenAndServe(":3333", LoggerMiddleware(handler))
if errors.Is(err, http.ErrServerClosed) {
fmt.Printf("server closed\n")
} else if err != nil {
Expand Down

0 comments on commit dd8672c

Please sign in to comment.