Skip to content

Commit

Permalink
refactored files around
Browse files Browse the repository at this point in the history
  • Loading branch information
CommanderStorm committed Oct 16, 2023
1 parent e5793e1 commit d48cad0
Show file tree
Hide file tree
Showing 5 changed files with 82 additions and 79 deletions.
43 changes: 1 addition & 42 deletions server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"net"
"net/http"
"net/textproto"
"strings"
"time"

"github.com/TUM-Dev/Campus-Backend/server/utils"
Expand All @@ -24,10 +23,8 @@ import (
"github.com/soheilhy/cmux"
"golang.org/x/sync/errgroup"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)

const httpPort = ":50051"
Expand Down Expand Up @@ -136,49 +133,11 @@ func addMethodNameInterceptor(ctx context.Context, method string, req interface{

// errorHandler translates gRPC raised by the backend into HTTP errors.
func errorHandler(_ context.Context, _ *runtime.ServeMux, _ runtime.Marshaler, w http.ResponseWriter, _ *http.Request, err error) {
errorResp := errorResponse{Error: "Internal Server Error", StatusCode: http.StatusInternalServerError}

if strings.HasPrefix(err.Error(), "no device id") {
errorResp.Error = "Not Authorized"
errorResp.StatusCode = http.StatusForbidden
}

if s, ok := status.FromError(err); ok {
switch s.Code() {
case codes.NotFound:
errorResp.Error = "Not Found"
errorResp.StatusCode = http.StatusNotFound
case codes.Unimplemented:
errorResp.Error = "Not Implemented"
errorResp.StatusCode = http.StatusNotImplemented
case codes.InvalidArgument:
errorResp.Error = "Invalid Argument"
errorResp.StatusCode = http.StatusBadRequest
case codes.Internal:
errorResp.Error = "Internal Server Error"
errorResp.StatusCode = http.StatusInternalServerError
}

if s.Message() != "" {
errorResp.Error = s.Message()
}

if s.Details() != nil && len(s.Details()) > 0 {
errorResp.Details = s.Details()
}
}

errorResp := utils.GrpcErrorToWebError(err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(errorResp.StatusCode)

if err = json.NewEncoder(w).Encode(errorResp); err != nil {
log.WithError(err).Error("Marshal error response failed")
return
}
}

type errorResponse struct {
Error string `json:"error"`
Details []interface{} `json:"details,omitempty"`
StatusCode int `json:"-"`
}
12 changes: 0 additions & 12 deletions server/migrate.go

This file was deleted.

32 changes: 32 additions & 0 deletions server/utils/db.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package utils

import (
"os"

"github.com/TUM-Dev/Campus-Backend/server/backend/migration"
gormlogrus "github.com/onrik/gorm-logrus"
log "github.com/sirupsen/logrus"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)

// SetupDB connects to the database and migrates it if necessary
func SetupDB() *gorm.DB {
dbHost := os.Getenv("DB_DSN")
if dbHost == "" {
log.Fatal("Failed to start! The 'DB_DSN' environment variable is not defined. Take a look at the README.md for more details.")
}

log.Info("Connecting to dsn")
db, err := gorm.Open(mysql.Open(dbHost), &gorm.Config{Logger: gormlogrus.New()})
if err != nil {
log.WithError(err).Fatal("failed to connect database")
}

// Migrate the schema
// currently not activated as
if err := migration.New(db, false).Migrate(); err != nil {
log.WithError(err).Fatal("Failed to migrate database")
}
return db
}
49 changes: 49 additions & 0 deletions server/utils/grpc_to_web.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package utils

import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"net/http"
"strings"
)

func GrpcErrorToWebError(err error) ErrorResponse {
errorResp := ErrorResponse{Error: "Internal Server Error", StatusCode: http.StatusInternalServerError}

if strings.HasPrefix(err.Error(), "no device id") {
errorResp.Error = "Not Authorized"
errorResp.StatusCode = http.StatusForbidden
}

if s, ok := status.FromError(err); ok {
switch s.Code() {
case codes.NotFound:
errorResp.Error = "Not Found"
errorResp.StatusCode = http.StatusNotFound
case codes.Unimplemented:
errorResp.Error = "Not Implemented"
errorResp.StatusCode = http.StatusNotImplemented
case codes.InvalidArgument:
errorResp.Error = "Invalid Argument"
errorResp.StatusCode = http.StatusBadRequest
case codes.Internal:
errorResp.Error = "Internal Server Error"
errorResp.StatusCode = http.StatusInternalServerError
}

if s.Message() != "" {
errorResp.Error = s.Message()
}

if s.Details() != nil && len(s.Details()) > 0 {
errorResp.Details = s.Details()
}
}
return errorResp
}

type ErrorResponse struct {
Error string `json:"error"`
Details []interface{} `json:"details,omitempty"`
StatusCode int `json:"-"`
}
25 changes: 0 additions & 25 deletions server/utils/utils.go → server/utils/telemetry.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,37 +3,12 @@ package utils
import (
"os"

"github.com/TUM-Dev/Campus-Backend/server/backend/migration"
"github.com/TUM-Dev/Campus-Backend/server/env"
"github.com/getsentry/sentry-go"
"github.com/makasim/sentryhook"
gormlogrus "github.com/onrik/gorm-logrus"
log "github.com/sirupsen/logrus"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)

// SetupDB connects to the database and migrates it if necessary
func SetupDB() *gorm.DB {
dbHost := os.Getenv("DB_DSN")
if dbHost == "" {
log.Fatal("Failed to start! The 'DB_DSN' environment variable is not defined. Take a look at the README.md for more details.")
}

log.Info("Connecting to dsn")
db, err := gorm.Open(mysql.Open(dbHost), &gorm.Config{Logger: gormlogrus.New()})
if err != nil {
log.WithError(err).Fatal("failed to connect database")
}

// Migrate the schema
// currently not activated as
if err := migration.New(db, false).Migrate(); err != nil {
log.WithError(err).Fatal("Failed to migrate database")
}
return db
}

// SetupTelemetry initializes our telemetry stack
// - sentry to be connected with log
// - logrus to
Expand Down

0 comments on commit d48cad0

Please sign in to comment.