Skip to content

Commit

Permalink
fix: create .json files
Browse files Browse the repository at this point in the history
  • Loading branch information
led0nk committed May 10, 2024
1 parent d2735fc commit 8d177a4
Show file tree
Hide file tree
Showing 31 changed files with 1,938 additions and 0 deletions.
121 changes: 121 additions & 0 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
package main

import (
"context"
"errors"
"flag"
"net/url"
"os"
"time"

"github.com/joho/godotenv"
v1 "github.com/led0nk/guestbook/api/v1"
"github.com/led0nk/guestbook/cmd/utils"
templates "github.com/led0nk/guestbook/internal"
db "github.com/led0nk/guestbook/internal/database"
"github.com/led0nk/guestbook/internal/database/jsondb"
"github.com/led0nk/guestbook/internal/mailer"
"github.com/led0nk/guestbook/token"
"github.com/rs/zerolog"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
"go.opentelemetry.io/otel/sdk/metric"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)

func main() {
logger := zerolog.New(
zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339},
).Level(zerolog.TraceLevel).With().Timestamp().Caller().Logger()
var (
addr = flag.String("addr", "localhost:8080", "server port")
grpcaddr = flag.String("grpcaddr", "localhost:4317", "grpc address")
dbase = flag.String("db", "file://testdata", "path to database")
envStr = flag.String("envvar's", "testdata/.env", "path to .env-file")
domain = flag.String("domain", "127.0.0.1", "given domain for cookies/mail")
bStore db.GuestBookStore
uStore db.UserStore
tStore db.TokenStore
)
flag.Parse()

u, err := url.Parse(*dbase)
if err != nil {
panic(err)
}
switch u.Scheme {
case "file":
filepath := u.Host + u.Path
bStore, err = jsondb.CreateBookStorage(filepath + "/entries.json")
if err != nil {
logger.Error().Err(errors.New("db")).Msg(err.Error())
}

uStore, err = jsondb.CreateUserStorage(filepath + "/user.json")
if err != nil {
logger.Error().Err(errors.New("db")).Msg(err.Error())
}
default:
logger.Error().Err(errors.New("db")).Msg("no database provided")
os.Exit(1)
}

err = godotenv.Load(*envStr)
if err != nil {
logger.Error().Err(err).Msg("")
panic("bad mailer env")
}

ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()

//NOTE: grpc configuration
grpcOptions := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock()}
conn, err := grpc.NewClient(*grpcaddr, grpcOptions...)
if err != nil {
logger.Error().Err(err).Msg("")
os.Exit(1)
}
defer conn.Close()

//NOTE: tracing configuration
oteltraceExporter, err := otlptracegrpc.New(ctx, otlptracegrpc.WithGRPCConn(conn))
if err != nil {
logger.Error().Err(err).Msg("")
os.Exit(1)
}
tp := sdktrace.NewTracerProvider(sdktrace.WithSyncer(oteltraceExporter))
otel.SetTracerProvider(tp)

//NOTE: metrics configuration
otelmetricsExporter, err := otlpmetricgrpc.New(ctx, otlpmetricgrpc.WithGRPCConn(conn))
if err != nil {
logger.Error().Err(err).Msg("")
os.Exit(1)
}
mp := metric.NewMeterProvider(metric.WithReader(metric.NewPeriodicReader(otelmetricsExporter)))
otel.SetMeterProvider(mp)

//in memory
tokenStorage, err := token.CreateTokenService(os.Getenv("TOKENSECRET"))
if err != nil {
logger.Error().Err(err).Msg("")
}
tStore = tokenStorage

//create templatehandler
templates := templates.NewTemplateHandler()
//create mailerservice
utils.LoadEnv(logger)
mailer := mailer.NewMailer(
os.Getenv("EMAIL"),
os.Getenv("SMTPPW"),
os.Getenv("HOST"),
os.Getenv("PORT"))
//create Server
server := v1.NewServer(*addr, mailer, *domain, templates, logger, bStore, uStore, tStore)
server.ServeHTTP()
}
66 changes: 66 additions & 0 deletions cmd/utils/utilities.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package utils

import (
"math/rand"
"net/url"
"os"
"unicode"

"regexp"

"github.com/joho/godotenv"
"github.com/rs/zerolog"
)

func CheckFlag(flag *string, logger zerolog.Logger, fn func(string) (interface{}, error)) interface{} {
var rStore interface{}
u, err := url.Parse(*flag)
if err != nil {
panic(err)
}
logger.Info().Msg(u.String())
switch u.Scheme {
case "file":
logger.Info().Str("opening", u.Host+u.Path).Msg("")
storage, _ := fn(u.Host + u.Path)
rStore = storage
default:
panic("bad storage")
}
return rStore
}

// Create a Random String e.g. for Verification Code
func RandomString(l int) string {
var chars = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

randomString := make([]rune, l)
for i := range randomString {
randomString[i] = chars[rand.Intn(len(chars))]
}
return string(randomString)
}

func FormValueBool(s string) bool {
return s == "true"
}

func Capitalize(s string) string {
runes := []rune(s)
runes[0] = unicode.ToUpper(runes[0])
return string(runes)
}

// LoadEnv loads env vars from .env
func LoadEnv(logger zerolog.Logger) {
re := regexp.MustCompile(`^(.*` + "guestbook" + `)`)
cwd, _ := os.Getwd()
rootPath := re.Find([]byte(cwd))

err := godotenv.Load(string(rootPath) + `/testdata` + `/.env`)
if err != nil {
logger.Fatal().Err(err).Msg(cwd)

os.Exit(-1)
}
}
38 changes: 38 additions & 0 deletions internal/database/database.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package db

import (
"context"
"net/http"

"github.com/led0nk/guestbook/internal/model"

"github.com/google/uuid"
)

type GuestBookStore interface {
CreateEntry(context.Context, *model.GuestbookEntry) (uuid.UUID, error)
ListEntries(context.Context) ([]*model.GuestbookEntry, error)
DeleteEntry(context.Context, uuid.UUID) error
GetEntryByName(context.Context, string) ([]*model.GuestbookEntry, error)
GetEntryByID(context.Context, uuid.UUID) ([]*model.GuestbookEntry, error)
GetEntryBySnippet(context.Context, string) ([]*model.GuestbookEntry, error)
}

type UserStore interface {
CreateUser(context.Context, *model.User) (uuid.UUID, error)
GetUserByEmail(context.Context, string) (*model.User, error)
GetUserByID(context.Context, uuid.UUID) (*model.User, error)
UpdateUser(context.Context, *model.User) error
CreateVerificationCode(context.Context, uuid.UUID) error
CodeValidation(context.Context, uuid.UUID, string) (bool, error)
ListUser(context.Context) ([]*model.User, error)
DeleteUser(context.Context, uuid.UUID) error
}

type TokenStore interface {
CreateToken(context.Context, string, string, uuid.UUID, bool) (*http.Cookie, error)
DeleteToken(context.Context, uuid.UUID) error
GetTokenValue(context.Context, *http.Cookie) (uuid.UUID, error)
Valid(context.Context, string) (bool, error)
Refresh(context.Context, string) (*http.Cookie, error)
}
Loading

0 comments on commit 8d177a4

Please sign in to comment.