From c7955104ae54a58df9c1797fc7a076fca7d9220e Mon Sep 17 00:00:00 2001 From: Eden Kirin Date: Wed, 25 Oct 2023 08:28:44 +0200 Subject: [PATCH 1/4] Login form --- app/templates/pages/index.jet | 17 +++++++++++++++++ app/views/index.go | 30 ++++++++++++++++++++++++++---- app/views/router.go | 2 ++ 3 files changed, 45 insertions(+), 4 deletions(-) diff --git a/app/templates/pages/index.jet b/app/templates/pages/index.jet index 3b198aa..0b8a27e 100644 --- a/app/templates/pages/index.jet +++ b/app/templates/pages/index.jet @@ -4,6 +4,23 @@ {{ block mainContent() }} +
+
+
+ + +
+
+ + +
+ + +
+
+

Bacon ipsum dolor amet leberkas kevin meatball pork loin beef ribs prosciutto, turducken bacon bresaola tri-tip. Strip steak flank shankle, sirloin short ribs shoulder meatball pork chop kevin ribeye jowl ham pork belly turducken jerky. Flank tongue short loin ham hock brisket turducken tail filet mignon cupim. Pork capicola buffalo kevin jowl chicken. Filet mignon brisket pig, landjaeger sausage cow fatback drumstick chicken buffalo tenderloin spare ribs.

Swine shankle porchetta pancetta. Buffalo chicken turducken ground round kevin shoulder, salami pig t-bone beef ribs tri-tip tongue pork belly doner. Landjaeger meatloaf short loin biltong. Alcatra tongue shankle, tri-tip pancetta porchetta tenderloin corned beef pastrami rump. Bresaola chislic beef kielbasa sausage, ball tip burgdoggen boudin capicola short loin tenderloin buffalo landjaeger.

diff --git a/app/views/index.go b/app/views/index.go index e593df1..545de7f 100644 --- a/app/views/index.go +++ b/app/views/index.go @@ -1,11 +1,33 @@ package views -import "github.com/kataras/iris/v12" +import ( + "fmt" + + "github.com/kataras/iris/v12" +) func GetIndexPage(ctx iris.Context) { - params1 := []string{"param 1", "param 2", "param 3"} - ctx.ViewData("params1", params1) - ctx.ViewData("users", users) + if err := ctx.View("pages/index.jet"); err != nil { + showError(ctx, err) + return + } +} + +type loginForm struct { + Email string `form:"email"` + Password string `form:"password"` +} + +func PostIndexPage(ctx iris.Context) { + var form loginForm + err := ctx.ReadForm(&form) + if err != nil { + ctx.StopWithError(iris.StatusBadRequest, err) + return + } + + fmt.Println("email:", form.Email) + fmt.Println("password:", form.Password) if err := ctx.View("pages/index.jet"); err != nil { showError(ctx, err) diff --git a/app/views/router.go b/app/views/router.go index 56a51a9..3904d46 100644 --- a/app/views/router.go +++ b/app/views/router.go @@ -4,6 +4,8 @@ import "github.com/kataras/iris/v12" func CreateRouter(app *iris.Application) { app.Get("/", GetIndexPage) + app.Post("/", PostIndexPage) + app.Get("/users", GetUsersPage) app.Get("/about", GetAboutPage) } From 7fdf131d5346127dff133e6a2bccba264dd3b9bc Mon Sep 17 00:00:00 2001 From: Eden Kirin Date: Wed, 25 Oct 2023 10:56:38 +0200 Subject: [PATCH 2/4] Create redis session engine --- app/cfg/cfg.go | 23 ++++++++++++++++------- app/main.go | 38 ++++++++++++++++++++++++++++++++++++++ config.template.yaml | 23 +++++++++++++++-------- go.mod | 3 +++ go.sum | 7 +++++++ 5 files changed, 79 insertions(+), 15 deletions(-) diff --git a/app/cfg/cfg.go b/app/cfg/cfg.go index 3ed641a..776d891 100644 --- a/app/cfg/cfg.go +++ b/app/cfg/cfg.go @@ -10,13 +10,6 @@ import ( ) type configStruct struct { - Database struct { - Host string `yaml:"host"` - Port string `yaml:"port"` - Name string `yaml:"name"` - Username string `yaml:"username"` - Password string `yaml:"password" json:"-"` - } `yaml:"database"` Application struct { SecretKey string `yaml:"secretKey" json:"-"` LogLevel string `yaml:"logLevel"` @@ -27,6 +20,21 @@ type configStruct struct { IsProduction bool `yaml:"isProduction"` LoopDelay uint32 `yaml:"loopDelay"` } `yaml:"application"` + Database struct { + Host string `yaml:"host"` + Port string `yaml:"port"` + Name string `yaml:"name"` + Username string `yaml:"username"` + Password string `yaml:"password" json:"-"` + } `yaml:"database"` + Redis struct { + Host string `yaml:"host"` + Port int `yaml:"port"` + Username string `yaml:"username"` + Password string `yaml:"password" json:"-"` + Database string `yaml:"database"` + Prefix string `yaml:"prefix"` + } `yaml:"redis"` SMTP struct { Host string `yaml:"host"` Port int `yaml:"port"` @@ -81,6 +89,7 @@ func Init() { maskedCfg := Config maskedCfg.Database.Password = "**password hidden**" + maskedCfg.Redis.Password = "**password hidden**" maskedCfg.SMTP.Password = "**password hidden**" maskedCfg.Application.SecretKey = "**secret key hidden**" diff --git a/app/main.go b/app/main.go index ff92f4c..70d29c8 100644 --- a/app/main.go +++ b/app/main.go @@ -1,16 +1,53 @@ package main import ( + "fmt" "iris-test/app/cfg" "iris-test/app/db" "iris-test/app/logging" "iris-test/app/views" + "time" "github.com/kataras/iris/v12" + "github.com/kataras/iris/v12/sessions" + "github.com/kataras/iris/v12/sessions/sessiondb/redis" ) +var redisDB *redis.Database + +func createSessionEngine() *sessions.Sessions { + redisAddr := fmt.Sprintf("%s:%d", cfg.Config.Redis.Host, cfg.Config.Redis.Port) + + redisDB = redis.New(redis.Config{ + Network: "tcp", + Addr: redisAddr, + Timeout: time.Duration(30) * time.Second, + MaxActive: 10, + Username: cfg.Config.Redis.Username, + Password: cfg.Config.Redis.Password, + Database: cfg.Config.Redis.Database, + Prefix: cfg.Config.Redis.Prefix, + Driver: redis.GoRedis(), // defaults to this driver. + // To set a custom, existing go-redis client, use the "SetClient" method: + // Driver: redis.GoRedis().SetClient(customGoRedisClient) + }) + + sessions_engine := sessions.New(sessions.Config{ + Cookie: "_session_id", + Expires: 0, // defaults to 0: unlimited life. Another good value is: 45 * time.Minute, + AllowReclaim: true, + CookieSecureTLS: true, + }) + + sessions_engine.UseDatabase(redisDB) + + return sessions_engine +} + func createApp() *iris.Application { + sessions_engine := createSessionEngine() app := iris.New() + app.Use(sessions_engine.Handler()) app.RegisterView(iris.Jet("./app/templates", ".jet").Reload(true)) views.CreateRouter(app) return app @@ -22,5 +59,6 @@ func main() { db.InitDB() app := createApp() + defer redisDB.Close() app.Listen(":8000") } diff --git a/config.template.yaml b/config.template.yaml index 497b25d..8a1e085 100644 --- a/config.template.yaml +++ b/config.template.yaml @@ -1,11 +1,3 @@ -# Database credentials -database: - host: "localhost" - port: 5432 - name: "iristest" - username: "iristest" - password: "iristest" - application: secretKey: "secret-key" logLevel: info @@ -14,6 +6,21 @@ application: isProduction: false loopDelay: 3000 +database: + host: "localhost" + port: 5432 + name: "iristest" + username: "iristest" + password: "iristest" + +redis: + host: "localhost" + port: 6379 + username: "iristest" + password: "iristest" + database: "" + prefix: "myapp-" + smtp: host: "smtp-host" port: 587 diff --git a/go.mod b/go.mod index 1bc134d..d423183 100644 --- a/go.mod +++ b/go.mod @@ -19,6 +19,8 @@ require ( github.com/Shopify/goreferrer v0.0.0-20220729165902-8cddb4f5de06 // indirect github.com/andybalholm/brotli v1.0.6 // indirect github.com/aymerick/douceur v0.2.0 // indirect + github.com/cespare/xxhash/v2 v2.2.0 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/fatih/structs v1.1.0 // indirect github.com/flosch/pongo2/v4 v4.0.2 // indirect github.com/golang/snappy v0.0.4 // indirect @@ -41,6 +43,7 @@ require ( github.com/mailgun/raymond/v2 v2.0.48 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/microcosm-cc/bluemonday v1.0.26 // indirect + github.com/redis/go-redis/v9 v9.2.0 // indirect github.com/rogpeppe/go-internal v1.11.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/schollz/closestmatch v2.1.0+incompatible // indirect diff --git a/go.sum b/go.sum index 67f5d1e..0ce609f 100644 --- a/go.sum +++ b/go.sum @@ -16,9 +16,14 @@ github.com/andybalholm/brotli v1.0.6 h1:Yf9fFpf49Zrxb9NlQaluyE92/+X7UVHlhMNJN2sx github.com/andybalholm/brotli v1.0.6/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= +github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= +github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= +github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo= @@ -98,6 +103,8 @@ github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTS github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/redis/go-redis/v9 v9.2.0 h1:zwMdX0A4eVzse46YN18QhuDiM4uf3JmkOB4VZrdt5uI= +github.com/redis/go-redis/v9 v9.2.0/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M= github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= From 34b2f55cfc6f40c7af5f6748b3fca1be8b0b6ca8 Mon Sep 17 00:00:00 2001 From: Eden Kirin Date: Wed, 25 Oct 2023 17:55:36 +0200 Subject: [PATCH 3/4] Restructure app --- .air.toml | 2 +- app/{cfg/cfg.go => config.go} | 4 ++-- app/{db => }/db.go | 18 ++++++++---------- app/{logging => }/logging.go | 15 +++++++-------- app/main.go | 19 ++++++++----------- 5 files changed, 26 insertions(+), 32 deletions(-) rename app/{cfg/cfg.go => config.go} (98%) rename app/{db => }/db.go (75%) rename app/{logging => }/logging.go (67%) diff --git a/.air.toml b/.air.toml index c2289e9..12c77a1 100644 --- a/.air.toml +++ b/.air.toml @@ -5,7 +5,7 @@ tmp_dir = "tmp" [build] args_bin = [] bin = "./tmp/main" -cmd = "go build -o ./tmp/main ./app/main.go" +cmd = "go build -o ./tmp/main ./app/." delay = 1000 exclude_dir = ["assets", "tmp", "vendor", "testdata", "build"] exclude_file = [] diff --git a/app/cfg/cfg.go b/app/config.go similarity index 98% rename from app/cfg/cfg.go rename to app/config.go index 776d891..d62ac2b 100644 --- a/app/cfg/cfg.go +++ b/app/config.go @@ -1,4 +1,4 @@ -package cfg +package main import ( "fmt" @@ -78,7 +78,7 @@ func readEnv(cfg *configStruct) { } } -func Init() { +func InitCfg() { cfgFile := os.Getenv("MAILSENDER_CONFIG") if cfgFile == "" { cfgFile = DEFAULT_CONFIG_FILE diff --git a/app/db/db.go b/app/db.go similarity index 75% rename from app/db/db.go rename to app/db.go index 742030a..4beb7a7 100644 --- a/app/db/db.go +++ b/app/db.go @@ -1,9 +1,7 @@ -package db +package main import ( "fmt" - "iris-test/app/cfg" - "iris-test/app/logging" "strconv" "strings" "time" @@ -21,18 +19,18 @@ var DBConn *gorm.DB func InitDB() *gorm.DB { var connectionString = strings.Join([]string{ "postgres://", - cfg.Config.Database.Username, ":", - cfg.Config.Database.Password, "@", - cfg.Config.Database.Host, ":", - cfg.Config.Database.Port, "/", - cfg.Config.Database.Name, + Config.Database.Username, ":", + Config.Database.Password, "@", + Config.Database.Host, ":", + Config.Database.Port, "/", + Config.Database.Name, "?sslmode=disable", "&TimeZone=UTC", "&connect_timeout=", strconv.Itoa(DB_CONNECTION_TIMEOUT), }, "") var logLevel = gormLogger.Silent - if cfg.Config.Application.DebugSQL { + if Config.Application.DebugSQL { logLevel = gormLogger.Info } @@ -42,7 +40,7 @@ func InitDB() *gorm.DB { }) if err != nil { msg := fmt.Sprintf("Error connecting to database: %s. Terminating!", err) - logging.Error(msg) + Log.Error(msg) panic(msg) } diff --git a/app/logging/logging.go b/app/logging.go similarity index 67% rename from app/logging/logging.go rename to app/logging.go index b09cb43..a7eb76f 100644 --- a/app/logging/logging.go +++ b/app/logging.go @@ -1,10 +1,9 @@ -package logging +package main import ( "encoding/json" "fmt" "io" - "iris-test/app/cfg" "os" "github.com/sirupsen/logrus" @@ -28,10 +27,10 @@ func Warn(message string) { Log.Warn(message) } -func Init() { - logLevel, err := logrus.ParseLevel(cfg.Config.Application.LogLevel) +func InitLogging() { + logLevel, err := logrus.ParseLevel(Config.Application.LogLevel) if err != nil { - panic(fmt.Sprintf("Invalid configured logLevel: %s\n", cfg.Config.Application.LogLevel)) + panic(fmt.Sprintf("Invalid configured logLevel: %s\n", Config.Application.LogLevel)) } Log.SetLevel(logLevel) @@ -43,14 +42,14 @@ func Init() { DisableQuote: true, }) - LogFile := cfg.Config.Application.LogFile + LogFile := Config.Application.LogFile file, err := os.OpenFile( LogFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0655, ) if err != nil { - msg := fmt.Sprintf("Failed to log to file %s: %s", cfg.Config.Application.LogFile, err) + msg := fmt.Sprintf("Failed to log to file %s: %s", Config.Application.LogFile, err) Log.Warning(msg) panic(msg) } @@ -58,7 +57,7 @@ func Init() { mw := io.MultiWriter(os.Stdout, file) Log.SetOutput(mw) - configJson, err := json.Marshal(cfg.Config) + configJson, err := json.Marshal(Config) if err == nil { Info(fmt.Sprintf("Using config: %s", configJson)) } diff --git a/app/main.go b/app/main.go index 70d29c8..d7313bf 100644 --- a/app/main.go +++ b/app/main.go @@ -2,9 +2,6 @@ package main import ( "fmt" - "iris-test/app/cfg" - "iris-test/app/db" - "iris-test/app/logging" "iris-test/app/views" "time" @@ -16,17 +13,17 @@ import ( var redisDB *redis.Database func createSessionEngine() *sessions.Sessions { - redisAddr := fmt.Sprintf("%s:%d", cfg.Config.Redis.Host, cfg.Config.Redis.Port) + redisAddr := fmt.Sprintf("%s:%d", Config.Redis.Host, Config.Redis.Port) redisDB = redis.New(redis.Config{ Network: "tcp", Addr: redisAddr, Timeout: time.Duration(30) * time.Second, MaxActive: 10, - Username: cfg.Config.Redis.Username, - Password: cfg.Config.Redis.Password, - Database: cfg.Config.Redis.Database, - Prefix: cfg.Config.Redis.Prefix, + Username: Config.Redis.Username, + Password: Config.Redis.Password, + Database: Config.Redis.Database, + Prefix: Config.Redis.Prefix, Driver: redis.GoRedis(), // defaults to this driver. // To set a custom, existing go-redis client, use the "SetClient" method: // Driver: redis.GoRedis().SetClient(customGoRedisClient) @@ -54,9 +51,9 @@ func createApp() *iris.Application { } func main() { - cfg.Init() - logging.Init() - db.InitDB() + InitCfg() + InitLogging() + InitDB() app := createApp() defer redisDB.Close() From b143983d522102bdf9463817f701e83b4d00bd0e Mon Sep 17 00:00:00 2001 From: Eden Kirin Date: Wed, 25 Oct 2023 19:54:21 +0200 Subject: [PATCH 4/4] User list --- app/db.go | 3 ++ app/main.go | 45 +++++++++++++++++++- app/models/user.go | 18 ++++++++ app/repository/dao.go | 17 ++++++++ app/repository/pagination.go | 12 ++++++ app/repository/users.go | 45 ++++++++++++++++++++ app/templates/components/table_component.jet | 6 +-- app/views/users.go | 38 ++++------------- go.mod | 3 ++ go.sum | 7 +++ 10 files changed, 160 insertions(+), 34 deletions(-) create mode 100644 app/models/user.go create mode 100644 app/repository/dao.go create mode 100644 app/repository/pagination.go create mode 100644 app/repository/users.go diff --git a/app/db.go b/app/db.go index 4beb7a7..44116ca 100644 --- a/app/db.go +++ b/app/db.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "iris-test/app/repository" "strconv" "strings" "time" @@ -48,5 +49,7 @@ func InitDB() *gorm.DB { db, _ := DBConn.DB() db.SetConnMaxIdleTime(CONNECTION_MAX_IDLE_TIME) + repository.Dao = repository.CreateDAO(DBConn) + return DBConn } diff --git a/app/main.go b/app/main.go index d7313bf..2d10e24 100644 --- a/app/main.go +++ b/app/main.go @@ -3,9 +3,11 @@ package main import ( "fmt" "iris-test/app/views" + "os" "time" "github.com/kataras/iris/v12" + "github.com/kataras/iris/v12/middleware/accesslog" "github.com/kataras/iris/v12/sessions" "github.com/kataras/iris/v12/sessions/sessiondb/redis" ) @@ -41,10 +43,49 @@ func createSessionEngine() *sessions.Sessions { return sessions_engine } +func createAccessLog() *accesslog.AccessLog { + // Initialize a new access log middleware. + ac := accesslog.New(os.Stdout) + // Remove this line to disable logging to console: + // ac.AddOutput(os.Stdout) + + // The default configuration: + ac.Delim = '|' + ac.TimeFormat = "2006-01-02 15:04:05" + ac.Async = false + ac.IP = true + ac.BytesReceivedBody = true + ac.BytesSentBody = true + ac.BytesReceived = false + ac.BytesSent = false + ac.BodyMinify = true + ac.RequestBody = true + ac.ResponseBody = false + ac.KeepMultiLineError = true + ac.PanicLog = accesslog.LogHandler + + // Default line format if formatter is missing: + // Time|Latency|Code|Method|Path|IP|Path Params Query Fields|Bytes Received|Bytes Sent|Request|Response| + // + // Set Custom Formatter: + ac.SetFormatter(&accesslog.JSON{ + Indent: " ", + HumanTime: true, + }) + // ac.SetFormatter(&accesslog.CSV{}) + // ac.SetFormatter(&accesslog.Template{Text: "{{.Code}}"}) + + return ac +} + func createApp() *iris.Application { - sessions_engine := createSessionEngine() + sessionsEngine := createSessionEngine() + accessLog := createAccessLog() + app := iris.New() - app.Use(sessions_engine.Handler()) + app.Logger().SetLevel(Config.Application.LogLevel) + app.Use(sessionsEngine.Handler()) + app.UseRouter(accessLog.Handler) app.RegisterView(iris.Jet("./app/templates", ".jet").Reload(true)) views.CreateRouter(app) return app diff --git a/app/models/user.go b/app/models/user.go new file mode 100644 index 0000000..dd7c5b5 --- /dev/null +++ b/app/models/user.go @@ -0,0 +1,18 @@ +package models + +import "time" + +type User struct { + Id string `gorm:"type(uuid);unique"` + Email string `gorm:"unique"` + FirstName string + LastName string + Password string + IsActive bool + CreatedAt time.Time + UpdatedAt time.Time +} + +func (u *User) TableName() string { + return "users" +} diff --git a/app/repository/dao.go b/app/repository/dao.go new file mode 100644 index 0000000..8b68ec1 --- /dev/null +++ b/app/repository/dao.go @@ -0,0 +1,17 @@ +package repository + +import "gorm.io/gorm" + +type DAO struct { + db *gorm.DB + UsersRepository *UsersRepository +} + +var Dao DAO + +func CreateDAO(db *gorm.DB) DAO { + return DAO{ + db: db, + UsersRepository: CreateUsersRepository(db), + } +} diff --git a/app/repository/pagination.go b/app/repository/pagination.go new file mode 100644 index 0000000..3b1c3eb --- /dev/null +++ b/app/repository/pagination.go @@ -0,0 +1,12 @@ +package repository + +type Pagination struct { + PageSize int + Page int +} + +func (p *Pagination) New() *Pagination { + p.PageSize = 50 + p.Page = 1 + return p +} diff --git a/app/repository/users.go b/app/repository/users.go new file mode 100644 index 0000000..5515f73 --- /dev/null +++ b/app/repository/users.go @@ -0,0 +1,45 @@ +package repository + +import ( + "iris-test/app/models" + + "gorm.io/gorm" +) + +type UsersRepository struct { + db *gorm.DB +} + +type UserFilter struct { + IsActive *bool +} + +func CreateUsersRepository(db *gorm.DB) *UsersRepository { + return &UsersRepository{db} +} + +func applyFilter(db *gorm.DB, filter *UserFilter) *gorm.DB { + query := db + + // if filter.State != "" { + // query = query.Where("state = ?", filter.State) + // } + // if filter.SendAt_lt != nil { + // query = query.Where("send_at < ?", filter.SendAt_lt) + // } + // if filter.SendAt_notNull != nil { + // query = query.Not(map[string]interface{}{"send_at": nil}) + // } + + return query +} + +func (repository *UsersRepository) List(filter *UserFilter) *[]models.User { + var users []models.User + + query := repository.db.Model(&models.User{}) + query = applyFilter(query, filter) + query.Find(&users) + + return &users +} diff --git a/app/templates/components/table_component.jet b/app/templates/components/table_component.jet index 26dcb29..564ad1e 100644 --- a/app/templates/components/table_component.jet +++ b/app/templates/components/table_component.jet @@ -5,9 +5,9 @@ {{ range users }} - {{ .firstName }} - {{ .lastName }} - {{ .email }} + {{ .FirstName }} + {{ .LastName }} + {{ .Email }} {{ end }} diff --git a/app/views/users.go b/app/views/users.go index 15e9af1..ed34041 100644 --- a/app/views/users.go +++ b/app/views/users.go @@ -1,39 +1,19 @@ package views -import "github.com/kataras/iris/v12" +import ( + "iris-test/app/repository" -type User struct { - firstName string - lastName string - email string -} - -var users = []User{ - { - firstName: "Pero", - lastName: "Perić", - email: "pero@gmail.com", - }, - { - firstName: "Mirko", - lastName: "Mirković", - email: "mirko@gmail.com", - }, - { - firstName: "Ivo", - lastName: "Ivić", - email: "ivo@gmail.com", - }, - { - firstName: "Slavko", - lastName: "Slavković", - email: "slavko@gmail.com", - }, -} + "github.com/kataras/iris/v12" +) func GetUsersPage(ctx iris.Context) { params1 := []string{"param 1", "param 2", "param 3"} ctx.ViewData("params1", params1) + + userRepository := repository.Dao.UsersRepository + + users := userRepository.List(&repository.UserFilter{}) + ctx.ViewData("users", users) if err := ctx.View("pages/users.jet"); err != nil { diff --git a/go.mod b/go.mod index d423183..f44610b 100644 --- a/go.mod +++ b/go.mod @@ -34,6 +34,7 @@ require ( github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/now v1.1.5 // indirect github.com/josharian/intern v1.0.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect github.com/kataras/blocks v0.0.8 // indirect github.com/kataras/golog v0.1.9 // indirect github.com/kataras/pio v0.0.12 // indirect @@ -43,6 +44,8 @@ require ( github.com/mailgun/raymond/v2 v2.0.48 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/microcosm-cc/bluemonday v1.0.26 // indirect + github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect github.com/redis/go-redis/v9 v9.2.0 // indirect github.com/rogpeppe/go-internal v1.11.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect diff --git a/go.sum b/go.sum index 0ce609f..cad4b7f 100644 --- a/go.sum +++ b/go.sum @@ -42,6 +42,7 @@ github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4= github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY= @@ -66,6 +67,8 @@ github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/kataras/blocks v0.0.8 h1:MrpVhoFTCR2v1iOOfGng5VJSILKeZZI+7NGfxEh3SUM= github.com/kataras/blocks v0.0.8/go.mod h1:9Jm5zx6BB+06NwA+OhTbHW1xkMOYxahnqTN5DveZ2Yg= github.com/kataras/golog v0.1.9 h1:vLvSDpP7kihFGKFAvBSofYo7qZNULYSHOH2D7rPTKJk= @@ -100,6 +103,10 @@ github.com/microcosm-cc/bluemonday v1.0.26 h1:xbqSvqzQMeEHCqMi64VAs4d8uy6Mequs3r github.com/microcosm-cc/bluemonday v1.0.26/go.mod h1:JyzOCs9gkyQyjs+6h10UEVSe02CGwkhd72Xdqh78TWs= github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=