detached cf93cff

Refactor and simplify the project structure between the server and the

client.
commit
cf93cff5b2788db43cc4461654288e46f60c0ed7
author
bnema · · 2023-10-25 08:38 UTC
parent
3c2b781
signature
unsigned
37 files · +162 -144
M cmd/cli/main.go +16 -3
@@ -3,14 +3,27 @@ package main
33 import (
44 "fmt"
55
6- "github.com/bnema/gordon/internal/app"
76 "github.com/bnema/gordon/internal/cli"
7+ "github.com/bnema/gordon/internal/cli/cmd"
8+ "github.com/spf13/cobra"
89 )
910
11+var rootCmd = &cobra.Command{Use: "gordon"}
12+
13+func InitializeCommands(a *cli.App) {
14+ // rootCmd.AddCommand(cmd.NewHelloCommand(a))
15+ rootCmd.AddCommand(cmd.NewPingCommand(a))
16+}
17+
18+func Execute(a *cli.App) {
19+ InitializeCommands(a)
20+ cobra.CheckErr(rootCmd.Execute())
21+}
22+
1023 func main() {
11- a, err := app.NewClientApp()
24+ a, err := cli.NewClientApp()
1225 if err != nil {
1326 fmt.Println("Error initializing app:", err)
1427 }
15- cli.Execute(a)
28+ Execute(a)
1629 }
@@ -3,14 +3,27 @@ package main
3 import (3 import (
4 "fmt"4 "fmt"
5 5
6- "github.com/bnema/gordon/internal/app"
7 "github.com/bnema/gordon/internal/cli"6 "github.com/bnema/gordon/internal/cli"
7+ "github.com/bnema/gordon/internal/cli/cmd"
8+ "github.com/spf13/cobra"
8 )9 )
9 10
11+var rootCmd = &cobra.Command{Use: "gordon"}
12+
13+func InitializeCommands(a *cli.App) {
14+ // rootCmd.AddCommand(cmd.NewHelloCommand(a))
15+ rootCmd.AddCommand(cmd.NewPingCommand(a))
16+}
17+
18+func Execute(a *cli.App) {
19+ InitializeCommands(a)
20+ cobra.CheckErr(rootCmd.Execute())
21+}
22+
10 func main() {23 func main() {
11- a, err := app.NewClientApp()24+ a, err := cli.NewClientApp()
12 if err != nil {25 if err != nil {
13 fmt.Println("Error initializing app:", err)26 fmt.Println("Error initializing app:", err)
14 }27 }
15- cli.Execute(a)28+ Execute(a)
16 }29 }
M cmd/srv/main.go +6 -6
@@ -9,26 +9,26 @@ import (
99
1010 "github.com/labstack/echo/v4"
1111
12- "github.com/bnema/gordon/internal/app"
1312 "github.com/bnema/gordon/internal/httpserve"
13+ "github.com/bnema/gordon/internal/server"
1414 "github.com/bnema/gordon/pkg/docker"
1515 )
1616
17-func cleanup(a *app.App) {
18- if err := app.CloseDB(a); err != nil {
17+func cleanup(a *server.App) {
18+ if err := server.CloseDB(a); err != nil {
1919 log.Fatal("Failed to close and backup database:", err)
2020 }
2121 }
2222
2323 func main() {
24- a := app.NewServerApp()
24+ a := server.NewServerApp()
2525
26- _, err := app.InitializeDB(a)
26+ _, err := server.InitializeDB(a)
2727 if err != nil {
2828 log.Fatal("Failed to initialize database:", err)
2929 }
3030
31- _, err = app.HandleNewTokenInitialization(a)
31+ _, err = server.HandleNewTokenInitialization(a)
3232 if err != nil {
3333 log.Print(err)
3434 }
@@ -9,26 +9,26 @@ import (
9 9
10 "github.com/labstack/echo/v4"10 "github.com/labstack/echo/v4"
11 11
12- "github.com/bnema/gordon/internal/app"
13 "github.com/bnema/gordon/internal/httpserve"12 "github.com/bnema/gordon/internal/httpserve"
13+ "github.com/bnema/gordon/internal/server"
14 "github.com/bnema/gordon/pkg/docker"14 "github.com/bnema/gordon/pkg/docker"
15 )15 )
16 16
17-func cleanup(a *app.App) {17+func cleanup(a *server.App) {
18- if err := app.CloseDB(a); err != nil {18+ if err := server.CloseDB(a); err != nil {
19 log.Fatal("Failed to close and backup database:", err)19 log.Fatal("Failed to close and backup database:", err)
20 }20 }
21 }21 }
22 22
23 func main() {23 func main() {
24- a := app.NewServerApp()24+ a := server.NewServerApp()
25 25
26- _, err := app.InitializeDB(a)26+ _, err := server.InitializeDB(a)
27 if err != nil {27 if err != nil {
28 log.Fatal("Failed to initialize database:", err)28 log.Fatal("Failed to initialize database:", err)
29 }29 }
30 30
31- _, err = app.HandleNewTokenInitialization(a)31+ _, err = server.HandleNewTokenInitialization(a)
32 if err != nil {32 if err != nil {
33 log.Print(err)33 log.Print(err)
34 }34 }
A internal/cli/appcli.go +18 -0
@@ -0,0 +1,18 @@
1+package cli
2+
3+type App struct {
4+ Config Config
5+}
6+
7+type Config struct {
8+ General GeneralConfig `yaml:"General"`
9+ Http HttpConfig `yaml:"Http"`
10+}
11+
12+type GeneralConfig struct {
13+ Token string `yaml:"token"`
14+}
15+
16+type HttpConfig struct {
17+ BackendURL string `yaml:"backendURL"`
18+}
@@ -0,0 +1,18 @@
1+package cli
2+
3+type App struct {
4+ Config Config
5+}
6+
7+type Config struct {
8+ General GeneralConfig `yaml:"General"`
9+ Http HttpConfig `yaml:"Http"`
10+}
11+
12+type GeneralConfig struct {
13+ Token string `yaml:"token"`
14+}
15+
16+type HttpConfig struct {
17+ BackendURL string `yaml:"backendURL"`
18+}
D internal/cli/cli.go +0 -19
@@ -1,19 +0,0 @@
1-package cli
2-
3-import (
4- "github.com/bnema/gordon/internal/app"
5- "github.com/bnema/gordon/internal/cli/cmd"
6- "github.com/spf13/cobra"
7-)
8-
9-var rootCmd = &cobra.Command{Use: "gordon"}
10-
11-func InitializeCommands(a *app.App) {
12- // rootCmd.AddCommand(cmd.NewHelloCommand(a))
13- rootCmd.AddCommand(cmd.NewPingCommand(a))
14-}
15-
16-func Execute(a *app.App) {
17- InitializeCommands(a)
18- cobra.CheckErr(rootCmd.Execute())
19-}
@@ -1,19 +0,0 @@
1-package cli
2-
3-import (
4- "github.com/bnema/gordon/internal/app"
5- "github.com/bnema/gordon/internal/cli/cmd"
6- "github.com/spf13/cobra"
7-)
8-
9-var rootCmd = &cobra.Command{Use: "gordon"}
10-
11-func InitializeCommands(a *app.App) {
12- // rootCmd.AddCommand(cmd.NewHelloCommand(a))
13- rootCmd.AddCommand(cmd.NewPingCommand(a))
14-}
15-
16-func Execute(a *app.App) {
17- InitializeCommands(a)
18- cobra.CheckErr(rootCmd.Execute())
19-}
M internal/cli/cmd/ping.go +3 -2
@@ -3,13 +3,14 @@ package cmd
33 import (
44 "fmt"
55
6- "github.com/bnema/gordon/internal/app"
6+ "github.com/bnema/gordon/internal/cli"
77 "github.com/bnema/gordon/internal/cli/handler"
88 "github.com/bnema/gordon/internal/common"
9+
910 "github.com/spf13/cobra"
1011 )
1112
12-func NewPingCommand(a *app.App) *cobra.Command {
13+func NewPingCommand(a *cli.App) *cobra.Command {
1314 return &cobra.Command{
1415 Use: "ping",
1516 Short: "Send a ping request to the backend",
@@ -3,13 +3,14 @@ package cmd
3 import (3 import (
4 "fmt"4 "fmt"
5 5
6- "github.com/bnema/gordon/internal/app"6+ "github.com/bnema/gordon/internal/cli"
7 "github.com/bnema/gordon/internal/cli/handler"7 "github.com/bnema/gordon/internal/cli/handler"
8 "github.com/bnema/gordon/internal/common"8 "github.com/bnema/gordon/internal/common"
9+
9 "github.com/spf13/cobra"10 "github.com/spf13/cobra"
10 )11 )
11 12
12-func NewPingCommand(a *app.App) *cobra.Command {13+func NewPingCommand(a *cli.App) *cobra.Command {
13 return &cobra.Command{14 return &cobra.Command{
14 Use: "ping",15 Use: "ping",
15 Short: "Send a ping request to the backend",16 Short: "Send a ping request to the backend",
M internal/cli/cmd/serve.go +2 -2
@@ -3,14 +3,14 @@
33 package cmd
44
55 import (
6- "github.com/bnema/gordon/internal/app"
76 "github.com/bnema/gordon/internal/cli/handler"
7+ "github.com/bnema/gordon/internal/server"
88 "github.com/spf13/cobra"
99 )
1010
1111 // execute cmd/srv/main.go main function
1212
13-func NewServeCommand(a *app.App) *cobra.Command {
13+func NewServeCommand(a *server.App) *cobra.Command {
1414 return &cobra.Command{
1515 Use: "serve",
1616 Short: "Start the gordon server",
@@ -3,14 +3,14 @@
3 package cmd3 package cmd
4 4
5 import (5 import (
6- "github.com/bnema/gordon/internal/app"
7 "github.com/bnema/gordon/internal/cli/handler"6 "github.com/bnema/gordon/internal/cli/handler"
7+ "github.com/bnema/gordon/internal/server"
8 "github.com/spf13/cobra"8 "github.com/spf13/cobra"
9 )9 )
10 10
11 // execute cmd/srv/main.go main function11 // execute cmd/srv/main.go main function
12 12
13-func NewServeCommand(a *app.App) *cobra.Command {13+func NewServeCommand(a *server.App) *cobra.Command {
14 return &cobra.Command{14 return &cobra.Command{
15 Use: "serve",15 Use: "serve",
16 Short: "Start the gordon server",16 Short: "Start the gordon server",
M internal/cli/handler/http.go +3 -3
@@ -7,7 +7,7 @@ import (
77 "io"
88 "net/http"
99
10- "github.com/bnema/gordon/internal/app"
10+ "github.com/bnema/gordon/internal/cli"
1111 "github.com/bnema/gordon/internal/common"
1212 )
1313
@@ -39,9 +39,9 @@ type Response struct {
3939 }
4040
4141 // SendHTTPRequest sends the HTTP request
42-func SendHTTPRequest(a *app.App, rp *common.RequestPayload, endpoint string) (*Response, error) {
42+func SendHTTPRequest(a *cli.App, rp *common.RequestPayload, endpoint string) (*Response, error) {
4343 apiUrl := a.Config.Http.BackendURL + "/api"
44- token := a.Config.General.GordonToken
44+ token := a.Config.General.Token
4545
4646 // Prepare the entire RequestPayload, not just the inner Payload
4747 jsonPayload, err := json.Marshal(rp)
@@ -7,7 +7,7 @@ import (
7 "io"7 "io"
8 "net/http"8 "net/http"
9 9
10- "github.com/bnema/gordon/internal/app"10+ "github.com/bnema/gordon/internal/cli"
11 "github.com/bnema/gordon/internal/common"11 "github.com/bnema/gordon/internal/common"
12 )12 )
13 13
@@ -39,9 +39,9 @@ type Response struct {
39 }39 }
40 40
41 // SendHTTPRequest sends the HTTP request41 // SendHTTPRequest sends the HTTP request
42-func SendHTTPRequest(a *app.App, rp *common.RequestPayload, endpoint string) (*Response, error) {42+func SendHTTPRequest(a *cli.App, rp *common.RequestPayload, endpoint string) (*Response, error) {
43 apiUrl := a.Config.Http.BackendURL + "/api"43 apiUrl := a.Config.Http.BackendURL + "/api"
44- token := a.Config.General.GordonToken44+ token := a.Config.General.Token
45 45
46 // Prepare the entire RequestPayload, not just the inner Payload46 // Prepare the entire RequestPayload, not just the inner Payload
47 jsonPayload, err := json.Marshal(rp)47 jsonPayload, err := json.Marshal(rp)
M internal/cli/handler/startserver.go +2 -2
@@ -1,9 +1,9 @@
11 package handler
22
3-import "github.com/bnema/gordon/internal/app"
3+import "github.com/bnema/gordon/internal/server"
44
55 // execute cmd/srv/main.go main function
66
7-func StartServer(a *app.App) error {
7+func StartServer(a *server.App) error {
88 return nil
99 }
@@ -1,9 +1,9 @@
1 package handler1 package handler
2 2
3-import "github.com/bnema/gordon/internal/app"3+import "github.com/bnema/gordon/internal/server"
4 4
5 // execute cmd/srv/main.go main function5 // execute cmd/srv/main.go main function
6 6
7-func StartServer(a *app.App) error {7+func StartServer(a *server.App) error {
8 return nil8 return nil
9 }9 }
R internal/app/newclient.go → internal/cli/newclient.go +2 -2 renamed, 96% similar
@@ -1,4 +1,4 @@
1-package app
1+package cli
22
33 import (
44 "fmt"
@@ -86,7 +86,7 @@ func (config *Config) LoadClientConfig() (*Config, error) {
8686 fmt.Printf("Config file not found, creating it at %s\n", configFilePath)
8787
8888 config.Http.BackendURL = readUserInput("Enter the backend URL (e.g. https://gordon.mydomain.com):")
89- config.General.GordonToken = readUserInput("Enter the token (check your backend config.yml):")
89+ config.General.Token = readUserInput("Enter the token (check your backend config.yml):")
9090
9191 err = config.SaveConfig()
9292 if err != nil {
@@ -1,4 +1,4 @@
1-package app1+package cli
2 2
3 import (3 import (
4 "fmt"4 "fmt"
@@ -86,7 +86,7 @@ func (config *Config) LoadClientConfig() (*Config, error) {
86 fmt.Printf("Config file not found, creating it at %s\n", configFilePath)86 fmt.Printf("Config file not found, creating it at %s\n", configFilePath)
87 87
88 config.Http.BackendURL = readUserInput("Enter the backend URL (e.g. https://gordon.mydomain.com):")88 config.Http.BackendURL = readUserInput("Enter the backend URL (e.g. https://gordon.mydomain.com):")
89- config.General.GordonToken = readUserInput("Enter the token (check your backend config.yml):")89+ config.General.Token = readUserInput("Enter the token (check your backend config.yml):")
90 90
91 err = config.SaveConfig()91 err = config.SaveConfig()
92 if err != nil {92 if err != nil {
M internal/db/queries/account.go +4 -4
@@ -1,11 +1,11 @@
11 package queries
22
33 import (
4- "github.com/bnema/gordon/internal/app"
54 "github.com/bnema/gordon/internal/db"
5+ "github.com/bnema/gordon/internal/server"
66 )
77
8-func createDBAccount(a *app.App) (*db.Account, error) {
8+func createDBAccount(a *server.App) (*db.Account, error) {
99 account := &db.Account{
1010 ID: generateUUID(),
1111 }
@@ -17,7 +17,7 @@ func createDBAccount(a *app.App) (*db.Account, error) {
1717 return account, err
1818 }
1919
20-func CheckDBAccountExists(a *app.App, accountID string) (bool, error) {
20+func CheckDBAccountExists(a *server.App, accountID string) (bool, error) {
2121 var exists bool
2222 err := a.DB.QueryRow("SELECT EXISTS(SELECT 1 FROM account WHERE id = ?)", accountID).Scan(&exists)
2323 if err != nil {
@@ -26,7 +26,7 @@ func CheckDBAccountExists(a *app.App, accountID string) (bool, error) {
2626 return exists, nil
2727 }
2828
29-func PopulateAccountFromDB(a *app.App) error {
29+func PopulateAccountFromDB(a *server.App) error {
3030 rows, err := a.DB.Query("SELECT id, user_id FROM account")
3131 if err != nil {
3232 return err
@@ -1,11 +1,11 @@
1 package queries1 package queries
2 2
3 import (3 import (
4- "github.com/bnema/gordon/internal/app"
5 "github.com/bnema/gordon/internal/db"4 "github.com/bnema/gordon/internal/db"
5+ "github.com/bnema/gordon/internal/server"
6 )6 )
7 7
8-func createDBAccount(a *app.App) (*db.Account, error) {8+func createDBAccount(a *server.App) (*db.Account, error) {
9 account := &db.Account{9 account := &db.Account{
10 ID: generateUUID(),10 ID: generateUUID(),
11 }11 }
@@ -17,7 +17,7 @@ func createDBAccount(a *app.App) (*db.Account, error) {
17 return account, err17 return account, err
18 }18 }
19 19
20-func CheckDBAccountExists(a *app.App, accountID string) (bool, error) {20+func CheckDBAccountExists(a *server.App, accountID string) (bool, error) {
21 var exists bool21 var exists bool
22 err := a.DB.QueryRow("SELECT EXISTS(SELECT 1 FROM account WHERE id = ?)", accountID).Scan(&exists)22 err := a.DB.QueryRow("SELECT EXISTS(SELECT 1 FROM account WHERE id = ?)", accountID).Scan(&exists)
23 if err != nil {23 if err != nil {
@@ -26,7 +26,7 @@ func CheckDBAccountExists(a *app.App, accountID string) (bool, error) {
26 return exists, nil26 return exists, nil
27 }27 }
28 28
29-func PopulateAccountFromDB(a *app.App) error {29+func PopulateAccountFromDB(a *server.App) error {
30 rows, err := a.DB.Query("SELECT id, user_id FROM account")30 rows, err := a.DB.Query("SELECT id, user_id FROM account")
31 if err != nil {31 if err != nil {
32 return err32 return err
M internal/db/queries/inspectdb.go +2 -2
@@ -3,11 +3,11 @@ package queries
33 import (
44 "fmt"
55
6- "github.com/bnema/gordon/internal/app"
6+ "github.com/bnema/gordon/internal/server"
77 )
88
99 // InspectInMemoryDB inspects the in-memory database. (for debug purpose)
10-func InspectInMemoryDB(a *app.App) error {
10+func InspectInMemoryDB(a *server.App) error {
1111 memDb := a.DB
1212 // Query the sqlite_master table to get a list of all tables
1313 rows, err := memDb.Query("SELECT name FROM sqlite_master WHERE type='table'")
@@ -3,11 +3,11 @@ package queries
3 import (3 import (
4 "fmt"4 "fmt"
5 5
6- "github.com/bnema/gordon/internal/app"6+ "github.com/bnema/gordon/internal/server"
7 )7 )
8 8
9 // InspectInMemoryDB inspects the in-memory database. (for debug purpose)9 // InspectInMemoryDB inspects the in-memory database. (for debug purpose)
10-func InspectInMemoryDB(a *app.App) error {10+func InspectInMemoryDB(a *server.App) error {
11 memDb := a.DB11 memDb := a.DB
12 // Query the sqlite_master table to get a list of all tables12 // Query the sqlite_master table to get a list of all tables
13 rows, err := memDb.Query("SELECT name FROM sqlite_master WHERE type='table'")13 rows, err := memDb.Query("SELECT name FROM sqlite_master WHERE type='table'")
M internal/db/queries/provider.go +3 -3
@@ -1,11 +1,11 @@
11 package queries
22
33 import (
4- "github.com/bnema/gordon/internal/app"
54 "github.com/bnema/gordon/internal/db"
5+ "github.com/bnema/gordon/internal/server"
66 )
77
8-func createDBGitHubProvider(a *app.App, userInfo *GithubUserInfo) error {
8+func createDBGitHubProvider(a *server.App, userInfo *GithubUserInfo) error {
99 provider := &db.Provider{
1010 ID: generateUUID(),
1111 Email: userInfo.Emails[0],
@@ -20,7 +20,7 @@ func createDBGitHubProvider(a *app.App, userInfo *GithubUserInfo) error {
2020 return err
2121 }
2222
23-func PopulateProviderFromDB(a *app.App) error {
23+func PopulateProviderFromDB(a *server.App) error {
2424 rows, err := a.DB.Query("SELECT id, account_id, name, login, avatar_url, profile_url, email FROM provider")
2525 if err != nil {
2626 return err
@@ -1,11 +1,11 @@
1 package queries1 package queries
2 2
3 import (3 import (
4- "github.com/bnema/gordon/internal/app"
5 "github.com/bnema/gordon/internal/db"4 "github.com/bnema/gordon/internal/db"
5+ "github.com/bnema/gordon/internal/server"
6 )6 )
7 7
8-func createDBGitHubProvider(a *app.App, userInfo *GithubUserInfo) error {8+func createDBGitHubProvider(a *server.App, userInfo *GithubUserInfo) error {
9 provider := &db.Provider{9 provider := &db.Provider{
10 ID: generateUUID(),10 ID: generateUUID(),
11 Email: userInfo.Emails[0],11 Email: userInfo.Emails[0],
@@ -20,7 +20,7 @@ func createDBGitHubProvider(a *app.App, userInfo *GithubUserInfo) error {
20 return err20 return err
21 }21 }
22 22
23-func PopulateProviderFromDB(a *app.App) error {23+func PopulateProviderFromDB(a *server.App) error {
24 rows, err := a.DB.Query("SELECT id, account_id, name, login, avatar_url, profile_url, email FROM provider")24 rows, err := a.DB.Query("SELECT id, account_id, name, login, avatar_url, profile_url, email FROM provider")
25 if err != nil {25 if err != nil {
26 return err26 return err
M internal/db/queries/sessions.go +7 -7
@@ -5,12 +5,12 @@ import (
55 "fmt"
66 "time"
77
8- "github.com/bnema/gordon/internal/app"
98 "github.com/bnema/gordon/internal/db"
9+ "github.com/bnema/gordon/internal/server"
1010 )
1111
1212 // createSession creates a session for the user.
13-func createDBSession(a *app.App, browserInfo string, accessToken string, accountID string) error {
13+func createDBSession(a *server.App, browserInfo string, accessToken string, accountID string) error {
1414 expireTime := time.Now().Add(time.Hour * 24).Format(time.RFC3339)
1515 sessions := &db.Sessions{
1616 ID: generateUUID(),
@@ -32,7 +32,7 @@ func createDBSession(a *app.App, browserInfo string, accessToken string, account
3232 }
3333
3434 // GetDBUserSession gets the user session from the database based on the access token and browser info.
35-func GetDBUserSession(a *app.App, accessToken string, browserInfo string) (*db.Sessions, error) {
35+func GetDBUserSession(a *server.App, accessToken string, browserInfo string) (*db.Sessions, error) {
3636 query := "SELECT sessions.id, sessions.account_id, sessions.access_token, sessions.browser_info, sessions.expires, sessions.is_online FROM sessions INNER JOIN account ON sessions.account_id = account.id INNER JOIN provider ON account.id = provider.account_id WHERE sessions.access_token = ? AND sessions.browser_info = ?"
3737 err := a.DB.QueryRow(query, accessToken, browserInfo).Scan(&a.DBTables.Sessions.ID, &a.DBTables.Sessions.AccountID, &a.DBTables.Sessions.AccessToken, &a.DBTables.Sessions.BrowserInfo, &a.DBTables.Sessions.Expires, &a.DBTables.Sessions.IsOnline)
3838 if err != nil {
@@ -45,7 +45,7 @@ func GetDBUserSession(a *app.App, accessToken string, browserInfo string) (*db.S
4545 return &a.DBTables.Sessions, nil
4646 }
4747
48-func updateDBSession(a *app.App, accessToken string, browserInfo string) error {
48+func updateDBSession(a *server.App, accessToken string, browserInfo string) error {
4949 expireTime := time.Now().Add(time.Hour * 24).Format(time.RFC3339)
5050 query := "UPDATE sessions SET access_token = ?, expires = ? WHERE id = ?"
5151 _, err := a.DB.Exec(query, accessToken, expireTime, a.DBTables.Sessions.ID)
@@ -56,7 +56,7 @@ func updateDBSession(a *app.App, accessToken string, browserInfo string) error {
5656 return nil
5757 }
5858
59-func CreateOrUpdateDBSession(a *app.App, accessToken string, browserInfo string) error {
59+func CreateOrUpdateDBSession(a *server.App, accessToken string, browserInfo string) error {
6060 // Check if the session exists using the access token and browser info
6161 session, err := GetDBUserSession(a, accessToken, browserInfo)
6262 if err != nil && err != sql.ErrNoRows {
@@ -83,7 +83,7 @@ func CreateOrUpdateDBSession(a *app.App, accessToken string, browserInfo string)
8383 }
8484
8585 // SessionCleaner, time as a string
86-func SessionCleaner(a *app.App, currentTime string) error {
86+func SessionCleaner(a *server.App, currentTime string) error {
8787 query := "DELETE FROM sessions WHERE expires < ?"
8888 _, err := a.DB.Exec(query, currentTime)
8989 if err != nil {
@@ -93,7 +93,7 @@ func SessionCleaner(a *app.App, currentTime string) error {
9393 return nil
9494 }
9595
96-func GetSessionExpiration(a *app.App, accountID string, sessionID string, currentTime time.Time) (time.Time, error) {
96+func GetSessionExpiration(a *server.App, accountID string, sessionID string, currentTime time.Time) (time.Time, error) {
9797 var expirationTime string
9898 // with userID and sessionID we can get the expiration time
9999 query := "SELECT expires FROM sessions WHERE account_id = ? AND id = ?"
@@ -5,12 +5,12 @@ import (
5 "fmt"5 "fmt"
6 "time"6 "time"
7 7
8- "github.com/bnema/gordon/internal/app"
9 "github.com/bnema/gordon/internal/db"8 "github.com/bnema/gordon/internal/db"
9+ "github.com/bnema/gordon/internal/server"
10 )10 )
11 11
12 // createSession creates a session for the user.12 // createSession creates a session for the user.
13-func createDBSession(a *app.App, browserInfo string, accessToken string, accountID string) error {13+func createDBSession(a *server.App, browserInfo string, accessToken string, accountID string) error {
14 expireTime := time.Now().Add(time.Hour * 24).Format(time.RFC3339)14 expireTime := time.Now().Add(time.Hour * 24).Format(time.RFC3339)
15 sessions := &db.Sessions{15 sessions := &db.Sessions{
16 ID: generateUUID(),16 ID: generateUUID(),
@@ -32,7 +32,7 @@ func createDBSession(a *app.App, browserInfo string, accessToken string, account
32 }32 }
33 33
34 // GetDBUserSession gets the user session from the database based on the access token and browser info.34 // GetDBUserSession gets the user session from the database based on the access token and browser info.
35-func GetDBUserSession(a *app.App, accessToken string, browserInfo string) (*db.Sessions, error) {35+func GetDBUserSession(a *server.App, accessToken string, browserInfo string) (*db.Sessions, error) {
36 query := "SELECT sessions.id, sessions.account_id, sessions.access_token, sessions.browser_info, sessions.expires, sessions.is_online FROM sessions INNER JOIN account ON sessions.account_id = account.id INNER JOIN provider ON account.id = provider.account_id WHERE sessions.access_token = ? AND sessions.browser_info = ?"36 query := "SELECT sessions.id, sessions.account_id, sessions.access_token, sessions.browser_info, sessions.expires, sessions.is_online FROM sessions INNER JOIN account ON sessions.account_id = account.id INNER JOIN provider ON account.id = provider.account_id WHERE sessions.access_token = ? AND sessions.browser_info = ?"
37 err := a.DB.QueryRow(query, accessToken, browserInfo).Scan(&a.DBTables.Sessions.ID, &a.DBTables.Sessions.AccountID, &a.DBTables.Sessions.AccessToken, &a.DBTables.Sessions.BrowserInfo, &a.DBTables.Sessions.Expires, &a.DBTables.Sessions.IsOnline)37 err := a.DB.QueryRow(query, accessToken, browserInfo).Scan(&a.DBTables.Sessions.ID, &a.DBTables.Sessions.AccountID, &a.DBTables.Sessions.AccessToken, &a.DBTables.Sessions.BrowserInfo, &a.DBTables.Sessions.Expires, &a.DBTables.Sessions.IsOnline)
38 if err != nil {38 if err != nil {
@@ -45,7 +45,7 @@ func GetDBUserSession(a *app.App, accessToken string, browserInfo string) (*db.S
45 return &a.DBTables.Sessions, nil45 return &a.DBTables.Sessions, nil
46 }46 }
47 47
48-func updateDBSession(a *app.App, accessToken string, browserInfo string) error {48+func updateDBSession(a *server.App, accessToken string, browserInfo string) error {
49 expireTime := time.Now().Add(time.Hour * 24).Format(time.RFC3339)49 expireTime := time.Now().Add(time.Hour * 24).Format(time.RFC3339)
50 query := "UPDATE sessions SET access_token = ?, expires = ? WHERE id = ?"50 query := "UPDATE sessions SET access_token = ?, expires = ? WHERE id = ?"
51 _, err := a.DB.Exec(query, accessToken, expireTime, a.DBTables.Sessions.ID)51 _, err := a.DB.Exec(query, accessToken, expireTime, a.DBTables.Sessions.ID)
@@ -56,7 +56,7 @@ func updateDBSession(a *app.App, accessToken string, browserInfo string) error {
56 return nil56 return nil
57 }57 }
58 58
59-func CreateOrUpdateDBSession(a *app.App, accessToken string, browserInfo string) error {59+func CreateOrUpdateDBSession(a *server.App, accessToken string, browserInfo string) error {
60 // Check if the session exists using the access token and browser info60 // Check if the session exists using the access token and browser info
61 session, err := GetDBUserSession(a, accessToken, browserInfo)61 session, err := GetDBUserSession(a, accessToken, browserInfo)
62 if err != nil && err != sql.ErrNoRows {62 if err != nil && err != sql.ErrNoRows {
@@ -83,7 +83,7 @@ func CreateOrUpdateDBSession(a *app.App, accessToken string, browserInfo string)
83 }83 }
84 84
85 // SessionCleaner, time as a string85 // SessionCleaner, time as a string
86-func SessionCleaner(a *app.App, currentTime string) error {86+func SessionCleaner(a *server.App, currentTime string) error {
87 query := "DELETE FROM sessions WHERE expires < ?"87 query := "DELETE FROM sessions WHERE expires < ?"
88 _, err := a.DB.Exec(query, currentTime)88 _, err := a.DB.Exec(query, currentTime)
89 if err != nil {89 if err != nil {
@@ -93,7 +93,7 @@ func SessionCleaner(a *app.App, currentTime string) error {
93 return nil93 return nil
94 }94 }
95 95
96-func GetSessionExpiration(a *app.App, accountID string, sessionID string, currentTime time.Time) (time.Time, error) {96+func GetSessionExpiration(a *server.App, accountID string, sessionID string, currentTime time.Time) (time.Time, error) {
97 var expirationTime string97 var expirationTime string
98 // with userID and sessionID we can get the expiration time98 // with userID and sessionID we can get the expiration time
99 query := "SELECT expires FROM sessions WHERE account_id = ? AND id = ?"99 query := "SELECT expires FROM sessions WHERE account_id = ? AND id = ?"
M internal/db/queries/user.go +7 -7
@@ -4,8 +4,8 @@ import (
44 "database/sql"
55 "fmt"
66
7- "github.com/bnema/gordon/internal/app"
87 "github.com/bnema/gordon/internal/db"
8+ "github.com/bnema/gordon/internal/server"
99 "github.com/google/uuid"
1010 )
1111
@@ -22,7 +22,7 @@ type GithubUserInfo struct {
2222 }
2323
2424 // CreateUser creates a new user along with the associated account, provider, and session.
25-func CreateUser(a *app.App, accessToken string, browserInfo string, userInfo *GithubUserInfo) error {
25+func CreateUser(a *server.App, accessToken string, browserInfo string, userInfo *GithubUserInfo) error {
2626 // Check if a user already exists. If so, return an error.
2727 if exists, err := CheckDBUserExists(a); err != nil || exists {
2828 return fmt.Errorf("error checking user or user already exists: %v", err)
@@ -57,7 +57,7 @@ func CreateUser(a *app.App, accessToken string, browserInfo string, userInfo *Gi
5757 return createDBSession(a, browserInfo, accessToken, account.ID)
5858 }
5959
60-func createDBUser(a *app.App, userInfo *GithubUserInfo) (*db.User, error) {
60+func createDBUser(a *server.App, userInfo *GithubUserInfo) (*db.User, error) {
6161 user := &db.User{
6262 ID: generateUUID(),
6363 Name: userInfo.Login,
@@ -71,7 +71,7 @@ func createDBUser(a *app.App, userInfo *GithubUserInfo) (*db.User, error) {
7171 return user, err
7272 }
7373
74-func CheckDBUserExists(a *app.App) (bool, error) {
74+func CheckDBUserExists(a *server.App) (bool, error) {
7575 var userID string
7676 err := a.DB.QueryRow("SELECT id FROM user").Scan(&userID)
7777 if err != nil {
@@ -89,7 +89,7 @@ func CheckDBUserExists(a *app.App) (bool, error) {
8989 }
9090
9191 // If there is already a user, we compare the login and email to see if it is the same user
92-func CheckDBUserIsGood(a *app.App, userInfo *GithubUserInfo) (bool, error) {
92+func CheckDBUserIsGood(a *server.App, userInfo *GithubUserInfo) (bool, error) {
9393 login := userInfo.Login
9494 email := userInfo.Emails[0]
9595
@@ -110,7 +110,7 @@ func CheckDBUserIsGood(a *app.App, userInfo *GithubUserInfo) (bool, error) {
110110 return false, nil
111111 }
112112
113-func UpdateUser(a *app.App, accessToken string, browserInfo string, userInfo *GithubUserInfo) (*db.User, error) {
113+func UpdateUser(a *server.App, accessToken string, browserInfo string, userInfo *GithubUserInfo) (*db.User, error) {
114114
115115 err := CreateOrUpdateDBSession(a, accessToken, browserInfo)
116116 if err != nil {
@@ -129,7 +129,7 @@ func UpdateUser(a *app.App, accessToken string, browserInfo string, userInfo *Gi
129129
130130 }
131131
132-func GetAccountCount(a *app.App) (int, error) {
132+func GetAccountCount(a *server.App) (int, error) {
133133 var count int
134134 err := a.DB.QueryRow("SELECT COUNT(*) FROM account").Scan(&count)
135135 if err != nil {
@@ -4,8 +4,8 @@ import (
4 "database/sql"4 "database/sql"
5 "fmt"5 "fmt"
6 6
7- "github.com/bnema/gordon/internal/app"
8 "github.com/bnema/gordon/internal/db"7 "github.com/bnema/gordon/internal/db"
8+ "github.com/bnema/gordon/internal/server"
9 "github.com/google/uuid"9 "github.com/google/uuid"
10 )10 )
11 11
@@ -22,7 +22,7 @@ type GithubUserInfo struct {
22 }22 }
23 23
24 // CreateUser creates a new user along with the associated account, provider, and session.24 // CreateUser creates a new user along with the associated account, provider, and session.
25-func CreateUser(a *app.App, accessToken string, browserInfo string, userInfo *GithubUserInfo) error {25+func CreateUser(a *server.App, accessToken string, browserInfo string, userInfo *GithubUserInfo) error {
26 // Check if a user already exists. If so, return an error.26 // Check if a user already exists. If so, return an error.
27 if exists, err := CheckDBUserExists(a); err != nil || exists {27 if exists, err := CheckDBUserExists(a); err != nil || exists {
28 return fmt.Errorf("error checking user or user already exists: %v", err)28 return fmt.Errorf("error checking user or user already exists: %v", err)
@@ -57,7 +57,7 @@ func CreateUser(a *app.App, accessToken string, browserInfo string, userInfo *Gi
57 return createDBSession(a, browserInfo, accessToken, account.ID)57 return createDBSession(a, browserInfo, accessToken, account.ID)
58 }58 }
59 59
60-func createDBUser(a *app.App, userInfo *GithubUserInfo) (*db.User, error) {60+func createDBUser(a *server.App, userInfo *GithubUserInfo) (*db.User, error) {
61 user := &db.User{61 user := &db.User{
62 ID: generateUUID(),62 ID: generateUUID(),
63 Name: userInfo.Login,63 Name: userInfo.Login,
@@ -71,7 +71,7 @@ func createDBUser(a *app.App, userInfo *GithubUserInfo) (*db.User, error) {
71 return user, err71 return user, err
72 }72 }
73 73
74-func CheckDBUserExists(a *app.App) (bool, error) {74+func CheckDBUserExists(a *server.App) (bool, error) {
75 var userID string75 var userID string
76 err := a.DB.QueryRow("SELECT id FROM user").Scan(&userID)76 err := a.DB.QueryRow("SELECT id FROM user").Scan(&userID)
77 if err != nil {77 if err != nil {
@@ -89,7 +89,7 @@ func CheckDBUserExists(a *app.App) (bool, error) {
89 }89 }
90 90
91 // If there is already a user, we compare the login and email to see if it is the same user91 // If there is already a user, we compare the login and email to see if it is the same user
92-func CheckDBUserIsGood(a *app.App, userInfo *GithubUserInfo) (bool, error) {92+func CheckDBUserIsGood(a *server.App, userInfo *GithubUserInfo) (bool, error) {
93 login := userInfo.Login93 login := userInfo.Login
94 email := userInfo.Emails[0]94 email := userInfo.Emails[0]
95 95
@@ -110,7 +110,7 @@ func CheckDBUserIsGood(a *app.App, userInfo *GithubUserInfo) (bool, error) {
110 return false, nil110 return false, nil
111 }111 }
112 112
113-func UpdateUser(a *app.App, accessToken string, browserInfo string, userInfo *GithubUserInfo) (*db.User, error) {113+func UpdateUser(a *server.App, accessToken string, browserInfo string, userInfo *GithubUserInfo) (*db.User, error) {
114 114
115 err := CreateOrUpdateDBSession(a, accessToken, browserInfo)115 err := CreateOrUpdateDBSession(a, accessToken, browserInfo)
116 if err != nil {116 if err != nil {
@@ -129,7 +129,7 @@ func UpdateUser(a *app.App, accessToken string, browserInfo string, userInfo *Gi
129 129
130 }130 }
131 131
132-func GetAccountCount(a *app.App) (int, error) {132+func GetAccountCount(a *server.App) (int, error) {
133 var count int133 var count int
134 err := a.DB.QueryRow("SELECT COUNT(*) FROM account").Scan(&count)134 err := a.DB.QueryRow("SELECT COUNT(*) FROM account").Scan(&count)
135 if err != nil {135 if err != nil {
M internal/httpserve/handler/adminroutes.go +5 -5
@@ -5,8 +5,8 @@ import (
55
66 "net/http"
77
8- "github.com/bnema/gordon/internal/app"
98 "github.com/bnema/gordon/internal/httpserve/middleware"
9+ "github.com/bnema/gordon/internal/server"
1010 "github.com/bnema/gordon/internal/templating/render"
1111 "github.com/labstack/echo/v4"
1212 )
@@ -17,7 +17,7 @@ var (
1717 )
1818
1919 // GetLocalizedData returns the data for the localization
20-func GetLocalizedData(c echo.Context, a *app.App) (map[string]interface{}, error) {
20+func GetLocalizedData(c echo.Context, a *server.App) (map[string]interface{}, error) {
2121 lang := c.Get(middleware.LangKey)
2222
2323 if lang == nil {
@@ -34,7 +34,7 @@ func GetLocalizedData(c echo.Context, a *app.App) (map[string]interface{}, error
3434 }
3535
3636 // renderAdminPage is a generalized function to render admin pages
37-func renderAdminPage(c echo.Context, a *app.App, templateName string) error {
37+func renderAdminPage(c echo.Context, a *server.App, templateName string) error {
3838 data, err := GetLocalizedData(c, a)
3939 if err != nil {
4040 return err
@@ -54,11 +54,11 @@ func renderAdminPage(c echo.Context, a *app.App, templateName string) error {
5454 }
5555
5656 // AdminRoute is the route for the admin panel
57-func AdminRoute(c echo.Context, a *app.App) error {
57+func AdminRoute(c echo.Context, a *server.App) error {
5858 return renderAdminPage(c, a, "index.gohtml")
5959 }
6060
6161 // AdminManagerRoute is the route of the manager page
62-func AdminManagerRoute(c echo.Context, a *app.App) error {
62+func AdminManagerRoute(c echo.Context, a *server.App) error {
6363 return renderAdminPage(c, a, "manager.gohtml")
6464 }
@@ -5,8 +5,8 @@ import (
5 5
6 "net/http"6 "net/http"
7 7
8- "github.com/bnema/gordon/internal/app"
9 "github.com/bnema/gordon/internal/httpserve/middleware"8 "github.com/bnema/gordon/internal/httpserve/middleware"
9+ "github.com/bnema/gordon/internal/server"
10 "github.com/bnema/gordon/internal/templating/render"10 "github.com/bnema/gordon/internal/templating/render"
11 "github.com/labstack/echo/v4"11 "github.com/labstack/echo/v4"
12 )12 )
@@ -17,7 +17,7 @@ var (
17 )17 )
18 18
19 // GetLocalizedData returns the data for the localization19 // GetLocalizedData returns the data for the localization
20-func GetLocalizedData(c echo.Context, a *app.App) (map[string]interface{}, error) {20+func GetLocalizedData(c echo.Context, a *server.App) (map[string]interface{}, error) {
21 lang := c.Get(middleware.LangKey)21 lang := c.Get(middleware.LangKey)
22 22
23 if lang == nil {23 if lang == nil {
@@ -34,7 +34,7 @@ func GetLocalizedData(c echo.Context, a *app.App) (map[string]interface{}, error
34 }34 }
35 35
36 // renderAdminPage is a generalized function to render admin pages36 // renderAdminPage is a generalized function to render admin pages
37-func renderAdminPage(c echo.Context, a *app.App, templateName string) error {37+func renderAdminPage(c echo.Context, a *server.App, templateName string) error {
38 data, err := GetLocalizedData(c, a)38 data, err := GetLocalizedData(c, a)
39 if err != nil {39 if err != nil {
40 return err40 return err
@@ -54,11 +54,11 @@ func renderAdminPage(c echo.Context, a *app.App, templateName string) error {
54 }54 }
55 55
56 // AdminRoute is the route for the admin panel56 // AdminRoute is the route for the admin panel
57-func AdminRoute(c echo.Context, a *app.App) error {57+func AdminRoute(c echo.Context, a *server.App) error {
58 return renderAdminPage(c, a, "index.gohtml")58 return renderAdminPage(c, a, "index.gohtml")
59 }59 }
60 60
61 // AdminManagerRoute is the route of the manager page61 // AdminManagerRoute is the route of the manager page
62-func AdminManagerRoute(c echo.Context, a *app.App) error {62+func AdminManagerRoute(c echo.Context, a *server.App) error {
63 return renderAdminPage(c, a, "manager.gohtml")63 return renderAdminPage(c, a, "manager.gohtml")
64 }64 }
M internal/httpserve/handler/containers.go +9 -9
@@ -6,7 +6,7 @@ import (
66 "sync"
77 "time"
88
9- "github.com/bnema/gordon/internal/app"
9+ "github.com/bnema/gordon/internal/server"
1010 "github.com/bnema/gordon/internal/templating/load"
1111 "github.com/bnema/gordon/internal/templating/render"
1212 "github.com/bnema/gordon/pkg/docker"
@@ -69,7 +69,7 @@ type HumanReadableContainer struct {
6969 }
7070
7171 // renderHTML is a generalized function to render HTML
72-func renderHTML(c echo.Context, a *app.App, path, templateName string, data map[string]interface{}) error {
72+func renderHTML(c echo.Context, a *server.App, path, templateName string, data map[string]interface{}) error {
7373 rendererData, err := render.GetHTMLRenderer(path, templateName, a.TemplateFS, a)
7474 if err != nil {
7575 return err
@@ -82,7 +82,7 @@ func renderHTML(c echo.Context, a *app.App, path, templateName string, data map[
8282 }
8383
8484 // ActionSuccess returns the success HTML fragment
85-func ActionSuccess(a *app.App) string {
85+func ActionSuccess(a *server.App) string {
8686 successFragment, err := load.Fragment(a, "success")
8787 if err != nil {
8888 fmt.Println(err)
@@ -93,7 +93,7 @@ func ActionSuccess(a *app.App) string {
9393 }
9494
9595 // ImageManagerComponent handles the /image-manager route (HTMX route)
96-func ImageManagerComponent(c echo.Context, a *app.App) error {
96+func ImageManagerComponent(c echo.Context, a *server.App) error {
9797 images, err := docker.ListContainerImages()
9898 if err != nil {
9999 return sendError(c, err)
@@ -127,7 +127,7 @@ func ImageManagerComponent(c echo.Context, a *app.App) error {
127127 }
128128
129129 // ImageManagerDelete handles the /image-manager/delete route
130-func ImageManagerDelete(c echo.Context, a *app.App) error {
130+func ImageManagerDelete(c echo.Context, a *server.App) error {
131131 //
132132 ShortID := c.Param("ID")
133133
@@ -149,7 +149,7 @@ func ImageManagerDelete(c echo.Context, a *app.App) error {
149149 }
150150
151151 // ContainerManagerComponent handles the /container-manager route
152-func ContainerManagerComponent(c echo.Context, a *app.App) error {
152+func ContainerManagerComponent(c echo.Context, a *server.App) error {
153153 containers, err := docker.ListRunningContainers()
154154 if err != nil {
155155 return sendError(c, err)
@@ -196,7 +196,7 @@ func ContainerManagerComponent(c echo.Context, a *app.App) error {
196196 }
197197
198198 // ContainerManagerDelete handles the /container-manager/delete route
199-func ContainerManagerDelete(c echo.Context, a *app.App) error {
199+func ContainerManagerDelete(c echo.Context, a *server.App) error {
200200 err := docker.RemoveContainer(c.Param("ID"))
201201 if err != nil {
202202 return sendError(c, err)
@@ -205,7 +205,7 @@ func ContainerManagerDelete(c echo.Context, a *app.App) error {
205205 }
206206
207207 // ContainerManagerStop handles the /container-manager/stop route
208-func ContainerManagerStop(c echo.Context, a *app.App) error {
208+func ContainerManagerStop(c echo.Context, a *server.App) error {
209209 // Stop the container gracefully with a timeout
210210 stopped, err := docker.StopContainerGracefully(c.Param("ID"), 3*time.Second)
211211 if err != nil {
@@ -225,7 +225,7 @@ func ContainerManagerStop(c echo.Context, a *app.App) error {
225225 }
226226
227227 // ContainerManagerStart handles the /container-manager/start route
228-func ContainerManagerStart(c echo.Context, a *app.App) error {
228+func ContainerManagerStart(c echo.Context, a *server.App) error {
229229 err := docker.StartContainer(c.Param("ID"))
230230 if err != nil {
231231 return sendError(c, err)
@@ -6,7 +6,7 @@ import (
6 "sync"6 "sync"
7 "time"7 "time"
8 8
9- "github.com/bnema/gordon/internal/app"9+ "github.com/bnema/gordon/internal/server"
10 "github.com/bnema/gordon/internal/templating/load"10 "github.com/bnema/gordon/internal/templating/load"
11 "github.com/bnema/gordon/internal/templating/render"11 "github.com/bnema/gordon/internal/templating/render"
12 "github.com/bnema/gordon/pkg/docker"12 "github.com/bnema/gordon/pkg/docker"
@@ -69,7 +69,7 @@ type HumanReadableContainer struct {
69 }69 }
70 70
71 // renderHTML is a generalized function to render HTML71 // renderHTML is a generalized function to render HTML
72-func renderHTML(c echo.Context, a *app.App, path, templateName string, data map[string]interface{}) error {72+func renderHTML(c echo.Context, a *server.App, path, templateName string, data map[string]interface{}) error {
73 rendererData, err := render.GetHTMLRenderer(path, templateName, a.TemplateFS, a)73 rendererData, err := render.GetHTMLRenderer(path, templateName, a.TemplateFS, a)
74 if err != nil {74 if err != nil {
75 return err75 return err
@@ -82,7 +82,7 @@ func renderHTML(c echo.Context, a *app.App, path, templateName string, data map[
82 }82 }
83 83
84 // ActionSuccess returns the success HTML fragment84 // ActionSuccess returns the success HTML fragment
85-func ActionSuccess(a *app.App) string {85+func ActionSuccess(a *server.App) string {
86 successFragment, err := load.Fragment(a, "success")86 successFragment, err := load.Fragment(a, "success")
87 if err != nil {87 if err != nil {
88 fmt.Println(err)88 fmt.Println(err)
@@ -93,7 +93,7 @@ func ActionSuccess(a *app.App) string {
93 }93 }
94 94
95 // ImageManagerComponent handles the /image-manager route (HTMX route)95 // ImageManagerComponent handles the /image-manager route (HTMX route)
96-func ImageManagerComponent(c echo.Context, a *app.App) error {96+func ImageManagerComponent(c echo.Context, a *server.App) error {
97 images, err := docker.ListContainerImages()97 images, err := docker.ListContainerImages()
98 if err != nil {98 if err != nil {
99 return sendError(c, err)99 return sendError(c, err)
@@ -127,7 +127,7 @@ func ImageManagerComponent(c echo.Context, a *app.App) error {
127 }127 }
128 128
129 // ImageManagerDelete handles the /image-manager/delete route129 // ImageManagerDelete handles the /image-manager/delete route
130-func ImageManagerDelete(c echo.Context, a *app.App) error {130+func ImageManagerDelete(c echo.Context, a *server.App) error {
131 //131 //
132 ShortID := c.Param("ID")132 ShortID := c.Param("ID")
133 133
@@ -149,7 +149,7 @@ func ImageManagerDelete(c echo.Context, a *app.App) error {
149 }149 }
150 150
151 // ContainerManagerComponent handles the /container-manager route151 // ContainerManagerComponent handles the /container-manager route
152-func ContainerManagerComponent(c echo.Context, a *app.App) error {152+func ContainerManagerComponent(c echo.Context, a *server.App) error {
153 containers, err := docker.ListRunningContainers()153 containers, err := docker.ListRunningContainers()
154 if err != nil {154 if err != nil {
155 return sendError(c, err)155 return sendError(c, err)
@@ -196,7 +196,7 @@ func ContainerManagerComponent(c echo.Context, a *app.App) error {
196 }196 }
197 197
198 // ContainerManagerDelete handles the /container-manager/delete route198 // ContainerManagerDelete handles the /container-manager/delete route
199-func ContainerManagerDelete(c echo.Context, a *app.App) error {199+func ContainerManagerDelete(c echo.Context, a *server.App) error {
200 err := docker.RemoveContainer(c.Param("ID"))200 err := docker.RemoveContainer(c.Param("ID"))
201 if err != nil {201 if err != nil {
202 return sendError(c, err)202 return sendError(c, err)
@@ -205,7 +205,7 @@ func ContainerManagerDelete(c echo.Context, a *app.App) error {
205 }205 }
206 206
207 // ContainerManagerStop handles the /container-manager/stop route207 // ContainerManagerStop handles the /container-manager/stop route
208-func ContainerManagerStop(c echo.Context, a *app.App) error {208+func ContainerManagerStop(c echo.Context, a *server.App) error {
209 // Stop the container gracefully with a timeout209 // Stop the container gracefully with a timeout
210 stopped, err := docker.StopContainerGracefully(c.Param("ID"), 3*time.Second)210 stopped, err := docker.StopContainerGracefully(c.Param("ID"), 3*time.Second)
211 if err != nil {211 if err != nil {
@@ -225,7 +225,7 @@ func ContainerManagerStop(c echo.Context, a *app.App) error {
225 }225 }
226 226
227 // ContainerManagerStart handles the /container-manager/start route227 // ContainerManagerStart handles the /container-manager/start route
228-func ContainerManagerStart(c echo.Context, a *app.App) error {228+func ContainerManagerStart(c echo.Context, a *server.App) error {
229 err := docker.StartContainer(c.Param("ID"))229 err := docker.StartContainer(c.Param("ID"))
230 if err != nil {230 if err != nil {
231 return sendError(c, err)231 return sendError(c, err)
M internal/httpserve/handler/createcontainer.go +3 -3
@@ -4,7 +4,7 @@ import (
44 "fmt"
55 "net/http"
66
7- "github.com/bnema/gordon/internal/app"
7+ "github.com/bnema/gordon/internal/server"
88 "github.com/bnema/gordon/internal/templating/render"
99 "github.com/bnema/gordon/pkg/docker"
1010 "github.com/bnema/gordon/pkg/sanitize"
@@ -21,7 +21,7 @@ func FromShortIDToImageID(ShortID string) (string, error) {
2121 }
2222
2323 // CreateContainerRoute is the route for creating a new container
24-func CreateContainerGET(c echo.Context, a *app.App) error {
24+func CreateContainerGET(c echo.Context, a *server.App) error {
2525 // Retreive the ShortID of the image from the URL
2626 ShortID := c.Param("ID")
2727
@@ -67,7 +67,7 @@ func CreateContainerGET(c echo.Context, a *app.App) error {
6767 }
6868
6969 // CreateContainerPOST handles the create container form submission
70-func CreateContainerPOST(c echo.Context, a *app.App) error {
70+func CreateContainerPOST(c echo.Context, a *server.App) error {
7171 // Retreive the ShortID of the image from the URL
7272 ShortID := c.Param("ID")
7373
@@ -4,7 +4,7 @@ import (
4 "fmt"4 "fmt"
5 "net/http"5 "net/http"
6 6
7- "github.com/bnema/gordon/internal/app"7+ "github.com/bnema/gordon/internal/server"
8 "github.com/bnema/gordon/internal/templating/render"8 "github.com/bnema/gordon/internal/templating/render"
9 "github.com/bnema/gordon/pkg/docker"9 "github.com/bnema/gordon/pkg/docker"
10 "github.com/bnema/gordon/pkg/sanitize"10 "github.com/bnema/gordon/pkg/sanitize"
@@ -21,7 +21,7 @@ func FromShortIDToImageID(ShortID string) (string, error) {
21 }21 }
22 22
23 // CreateContainerRoute is the route for creating a new container23 // CreateContainerRoute is the route for creating a new container
24-func CreateContainerGET(c echo.Context, a *app.App) error {24+func CreateContainerGET(c echo.Context, a *server.App) error {
25 // Retreive the ShortID of the image from the URL25 // Retreive the ShortID of the image from the URL
26 ShortID := c.Param("ID")26 ShortID := c.Param("ID")
27 27
@@ -67,7 +67,7 @@ func CreateContainerGET(c echo.Context, a *app.App) error {
67 }67 }
68 68
69 // CreateContainerPOST handles the create container form submission69 // CreateContainerPOST handles the create container form submission
70-func CreateContainerPOST(c echo.Context, a *app.App) error {70+func CreateContainerPOST(c echo.Context, a *server.App) error {
71 // Retreive the ShortID of the image from the URL71 // Retreive the ShortID of the image from the URL
72 ShortID := c.Param("ID")72 ShortID := c.Param("ID")
73 73
M internal/httpserve/handler/editcontainer.go +3 -3
@@ -5,7 +5,7 @@ import (
55 "log"
66 "strings"
77
8- "github.com/bnema/gordon/internal/app"
8+ "github.com/bnema/gordon/internal/server"
99 "github.com/bnema/gordon/internal/templating/render"
1010 "github.com/bnema/gordon/pkg/docker"
1111 "github.com/labstack/echo/v4"
@@ -34,7 +34,7 @@ func generateOrderedYAML(infoMap map[string]interface{}) (string, error) {
3434 }
3535
3636 // ContainerManagerEditGET displays the edit container view
37-func ContainerManagerEditGET(c echo.Context, a *app.App) error {
37+func ContainerManagerEditGET(c echo.Context, a *server.App) error {
3838 containerID := c.Param("ID")
3939
4040 // Get the container info
@@ -149,7 +149,7 @@ func (tq *TransactionQueue) Execute() error {
149149 }
150150
151151 // ContainerManagerEditPOST handles the edit container form submission
152-func ContainerManagerEditPOST(c echo.Context, a *app.App) error {
152+func ContainerManagerEditPOST(c echo.Context, a *server.App) error {
153153 tq := &TransactionQueue{}
154154 oldContainerID := c.Param("ID")
155155
@@ -5,7 +5,7 @@ import (
5 "log"5 "log"
6 "strings"6 "strings"
7 7
8- "github.com/bnema/gordon/internal/app"8+ "github.com/bnema/gordon/internal/server"
9 "github.com/bnema/gordon/internal/templating/render"9 "github.com/bnema/gordon/internal/templating/render"
10 "github.com/bnema/gordon/pkg/docker"10 "github.com/bnema/gordon/pkg/docker"
11 "github.com/labstack/echo/v4"11 "github.com/labstack/echo/v4"
@@ -34,7 +34,7 @@ func generateOrderedYAML(infoMap map[string]interface{}) (string, error) {
34 }34 }
35 35
36 // ContainerManagerEditGET displays the edit container view36 // ContainerManagerEditGET displays the edit container view
37-func ContainerManagerEditGET(c echo.Context, a *app.App) error {37+func ContainerManagerEditGET(c echo.Context, a *server.App) error {
38 containerID := c.Param("ID")38 containerID := c.Param("ID")
39 39
40 // Get the container info40 // Get the container info
@@ -149,7 +149,7 @@ func (tq *TransactionQueue) Execute() error {
149 }149 }
150 150
151 // ContainerManagerEditPOST handles the edit container form submission151 // ContainerManagerEditPOST handles the edit container form submission
152-func ContainerManagerEditPOST(c echo.Context, a *app.App) error {152+func ContainerManagerEditPOST(c echo.Context, a *server.App) error {
153 tq := &TransactionQueue{}153 tq := &TransactionQueue{}
154 oldContainerID := c.Param("ID")154 oldContainerID := c.Param("ID")
155 155
M internal/httpserve/handler/endpoints.go +4 -4
@@ -6,13 +6,13 @@ import (
66 "io"
77 "net/http"
88
9- "github.com/bnema/gordon/internal/app"
109 "github.com/bnema/gordon/internal/common"
10+ "github.com/bnema/gordon/internal/server"
1111 "github.com/labstack/echo/v4"
1212 )
1313
1414 // Handle GET on /api/hello endpoint
15-func GetHello(c echo.Context, a *app.App) error {
15+func GetHello(c echo.Context, a *server.App) error {
1616 return c.JSON(http.StatusOK, "Hello, World!")
1717 }
1818
@@ -21,13 +21,13 @@ type InfoResponse struct {
2121 Version string `json:"version"`
2222 }
2323
24-func (info *InfoResponse) Populate(a *app.App) {
24+func (info *InfoResponse) Populate(a *server.App) {
2525 info.Uptime = a.GetUptime()
2626 info.Version = a.Config.GetVersion()
2727 }
2828
2929 // Handle GET on /api/ping endpoint
30-func GetInfos(c echo.Context, a *app.App) error {
30+func GetInfos(c echo.Context, a *server.App) error {
3131 fmt.Println("GET /api/ping")
3232 body, _ := io.ReadAll(c.Request().Body)
3333 fmt.Println("Request Body:", string(body))
@@ -6,13 +6,13 @@ import (
6 "io"6 "io"
7 "net/http"7 "net/http"
8 8
9- "github.com/bnema/gordon/internal/app"
10 "github.com/bnema/gordon/internal/common"9 "github.com/bnema/gordon/internal/common"
10+ "github.com/bnema/gordon/internal/server"
11 "github.com/labstack/echo/v4"11 "github.com/labstack/echo/v4"
12 )12 )
13 13
14 // Handle GET on /api/hello endpoint14 // Handle GET on /api/hello endpoint
15-func GetHello(c echo.Context, a *app.App) error {15+func GetHello(c echo.Context, a *server.App) error {
16 return c.JSON(http.StatusOK, "Hello, World!")16 return c.JSON(http.StatusOK, "Hello, World!")
17 }17 }
18 18
@@ -21,13 +21,13 @@ type InfoResponse struct {
21 Version string `json:"version"`21 Version string `json:"version"`
22 }22 }
23 23
24-func (info *InfoResponse) Populate(a *app.App) {24+func (info *InfoResponse) Populate(a *server.App) {
25 info.Uptime = a.GetUptime()25 info.Uptime = a.GetUptime()
26 info.Version = a.Config.GetVersion()26 info.Version = a.Config.GetVersion()
27 }27 }
28 28
29 // Handle GET on /api/ping endpoint29 // Handle GET on /api/ping endpoint
30-func GetInfos(c echo.Context, a *app.App) error {30+func GetInfos(c echo.Context, a *server.App) error {
31 fmt.Println("GET /api/ping")31 fmt.Println("GET /api/ping")
32 body, _ := io.ReadAll(c.Request().Body)32 body, _ := io.ReadAll(c.Request().Body)
33 fmt.Println("Request Body:", string(body))33 fmt.Println("Request Body:", string(body))
M internal/httpserve/handler/oauth.go +16 -12
@@ -8,9 +8,9 @@ import (
88 "net/http"
99 "os"
1010
11- "github.com/bnema/gordon/internal/app"
1211 "github.com/bnema/gordon/internal/db"
1312 "github.com/bnema/gordon/internal/db/queries"
13+ "github.com/bnema/gordon/internal/server"
1414 "github.com/bnema/gordon/internal/templating/render"
1515 "github.com/gorilla/sessions"
1616 _ "github.com/joho/godotenv/autoload"
@@ -21,17 +21,21 @@ import (
2121 var urlToken string
2222
2323 // compareGordonToken compares the token from the URL query parameter with the one from the config.yml
24-func CompareGordonToken(c echo.Context, a *app.App) error {
25- configToken := a.Config.General.GordonToken
24+func CompareGordonToken(c echo.Context, a *server.App) error {
25+ configToken, err := a.Config.GetToken()
26+ if err != nil {
27+ return err
28+ }
29+
2630 if urlToken != configToken {
27- // if token is not present or does not match the one from the config.yml
28- return fmt.Errorf("token is not valid")
31+ return fmt.Errorf("token is empty or not valid")
2932 }
33+
3034 return nil
3135 }
3236
3337 // RenderLoginPage renders the login.html template
34-func RenderLoginPage(c echo.Context, a *app.App) error {
38+func RenderLoginPage(c echo.Context, a *server.App) error {
3539 urlToken = c.QueryParam("token")
3640 data := map[string]interface{}{
3741 "Title": "Login",
@@ -53,7 +57,7 @@ func RenderLoginPage(c echo.Context, a *app.App) error {
5357 }
5458
5559 // StartOAuthGithub starts the Github OAuth flow
56-func StartOAuthGithub(c echo.Context, a *app.App) error {
60+func StartOAuthGithub(c echo.Context, a *server.App) error {
5761 // Check if the session is already here and valid before going for the oauth flow
5862 sess, err := getSession(c)
5963 if err != nil {
@@ -85,7 +89,7 @@ type Sessions struct {
8589 }
8690
8791 // OAuthCallback handles the callback response from Github OAuth
88-func OAuthCallback(c echo.Context, a *app.App) error {
92+func OAuthCallback(c echo.Context, a *server.App) error {
8993 redirectPath := a.Config.Admin.Path
9094
9195 accessToken, encodedState, err := parseQueryParams(c)
@@ -150,7 +154,7 @@ func getSession(c echo.Context) (*sessions.Session, error) {
150154 }
151155
152156 // handleUser handles the user creation or update
153-func handleUser(c echo.Context, a *app.App, accessToken, browserInfo string, userInfo *queries.GithubUserInfo) (*db.User, error) {
157+func handleUser(c echo.Context, a *server.App, accessToken, browserInfo string, userInfo *queries.GithubUserInfo) (*db.User, error) {
154158 userExists, err := queries.CheckDBUserExists(a)
155159 if err != nil {
156160 return nil, fmt.Errorf("could not check if user exists: %w", err)
@@ -191,7 +195,7 @@ func handleUser(c echo.Context, a *app.App, accessToken, browserInfo string, use
191195 }
192196
193197 // createUser creates a new user in the database
194-func createUser(a *app.App, accessToken, browserInfo string, userInfo *queries.GithubUserInfo) (*db.User, error) {
198+func createUser(a *server.App, accessToken, browserInfo string, userInfo *queries.GithubUserInfo) (*db.User, error) {
195199 err := queries.CreateUser(a, accessToken, browserInfo, userInfo)
196200 if err != nil {
197201 return nil, fmt.Errorf("could not create user: %w", err)
@@ -200,7 +204,7 @@ func createUser(a *app.App, accessToken, browserInfo string, userInfo *queries.G
200204 }
201205
202206 // updateUser updates an existing user in the database
203-func updateUser(a *app.App, accessToken, browserInfo string, userInfo *queries.GithubUserInfo) (*db.User, error) {
207+func updateUser(a *server.App, accessToken, browserInfo string, userInfo *queries.GithubUserInfo) (*db.User, error) {
204208 user, err := queries.UpdateUser(a, accessToken, browserInfo, userInfo)
205209 if err != nil {
206210 return nil, fmt.Errorf("could not update user: %w", err)
@@ -254,7 +258,7 @@ func fetchGithubAPI(url string, authHeader string, result interface{}) error {
254258 }
255259
256260 // githubGetUserDetails gets the user details from the Github API using the access token
257-func githubGetUserDetails(c echo.Context, a *app.App) (userInfo *queries.GithubUserInfo, err error) {
261+func githubGetUserDetails(c echo.Context, a *server.App) (userInfo *queries.GithubUserInfo, err error) {
258262 accessToken := c.QueryParam("access_token")
259263
260264 // Fetch user info
@@ -8,9 +8,9 @@ import (
8 "net/http"8 "net/http"
9 "os"9 "os"
10 10
11- "github.com/bnema/gordon/internal/app"
12 "github.com/bnema/gordon/internal/db"11 "github.com/bnema/gordon/internal/db"
13 "github.com/bnema/gordon/internal/db/queries"12 "github.com/bnema/gordon/internal/db/queries"
13+ "github.com/bnema/gordon/internal/server"
14 "github.com/bnema/gordon/internal/templating/render"14 "github.com/bnema/gordon/internal/templating/render"
15 "github.com/gorilla/sessions"15 "github.com/gorilla/sessions"
16 _ "github.com/joho/godotenv/autoload"16 _ "github.com/joho/godotenv/autoload"
@@ -21,17 +21,21 @@ import (
21 var urlToken string21 var urlToken string
22 22
23 // compareGordonToken compares the token from the URL query parameter with the one from the config.yml23 // compareGordonToken compares the token from the URL query parameter with the one from the config.yml
24-func CompareGordonToken(c echo.Context, a *app.App) error {24+func CompareGordonToken(c echo.Context, a *server.App) error {
25- configToken := a.Config.General.GordonToken25+ configToken, err := a.Config.GetToken()
26+ if err != nil {
27+ return err
28+ }
29+
26 if urlToken != configToken {30 if urlToken != configToken {
27- // if token is not present or does not match the one from the config.yml31+ return fmt.Errorf("token is empty or not valid")
28- return fmt.Errorf("token is not valid")
29 }32 }
33+
30 return nil34 return nil
31 }35 }
32 36
33 // RenderLoginPage renders the login.html template37 // RenderLoginPage renders the login.html template
34-func RenderLoginPage(c echo.Context, a *app.App) error {38+func RenderLoginPage(c echo.Context, a *server.App) error {
35 urlToken = c.QueryParam("token")39 urlToken = c.QueryParam("token")
36 data := map[string]interface{}{40 data := map[string]interface{}{
37 "Title": "Login",41 "Title": "Login",
@@ -53,7 +57,7 @@ func RenderLoginPage(c echo.Context, a *app.App) error {
53 }57 }
54 58
55 // StartOAuthGithub starts the Github OAuth flow59 // StartOAuthGithub starts the Github OAuth flow
56-func StartOAuthGithub(c echo.Context, a *app.App) error {60+func StartOAuthGithub(c echo.Context, a *server.App) error {
57 // Check if the session is already here and valid before going for the oauth flow61 // Check if the session is already here and valid before going for the oauth flow
58 sess, err := getSession(c)62 sess, err := getSession(c)
59 if err != nil {63 if err != nil {
@@ -85,7 +89,7 @@ type Sessions struct {
85 }89 }
86 90
87 // OAuthCallback handles the callback response from Github OAuth91 // OAuthCallback handles the callback response from Github OAuth
88-func OAuthCallback(c echo.Context, a *app.App) error {92+func OAuthCallback(c echo.Context, a *server.App) error {
89 redirectPath := a.Config.Admin.Path93 redirectPath := a.Config.Admin.Path
90 94
91 accessToken, encodedState, err := parseQueryParams(c)95 accessToken, encodedState, err := parseQueryParams(c)
@@ -150,7 +154,7 @@ func getSession(c echo.Context) (*sessions.Session, error) {
150 }154 }
151 155
152 // handleUser handles the user creation or update156 // handleUser handles the user creation or update
153-func handleUser(c echo.Context, a *app.App, accessToken, browserInfo string, userInfo *queries.GithubUserInfo) (*db.User, error) {157+func handleUser(c echo.Context, a *server.App, accessToken, browserInfo string, userInfo *queries.GithubUserInfo) (*db.User, error) {
154 userExists, err := queries.CheckDBUserExists(a)158 userExists, err := queries.CheckDBUserExists(a)
155 if err != nil {159 if err != nil {
156 return nil, fmt.Errorf("could not check if user exists: %w", err)160 return nil, fmt.Errorf("could not check if user exists: %w", err)
@@ -191,7 +195,7 @@ func handleUser(c echo.Context, a *app.App, accessToken, browserInfo string, use
191 }195 }
192 196
193 // createUser creates a new user in the database197 // createUser creates a new user in the database
194-func createUser(a *app.App, accessToken, browserInfo string, userInfo *queries.GithubUserInfo) (*db.User, error) {198+func createUser(a *server.App, accessToken, browserInfo string, userInfo *queries.GithubUserInfo) (*db.User, error) {
195 err := queries.CreateUser(a, accessToken, browserInfo, userInfo)199 err := queries.CreateUser(a, accessToken, browserInfo, userInfo)
196 if err != nil {200 if err != nil {
197 return nil, fmt.Errorf("could not create user: %w", err)201 return nil, fmt.Errorf("could not create user: %w", err)
@@ -200,7 +204,7 @@ func createUser(a *app.App, accessToken, browserInfo string, userInfo *queries.G
200 }204 }
201 205
202 // updateUser updates an existing user in the database206 // updateUser updates an existing user in the database
203-func updateUser(a *app.App, accessToken, browserInfo string, userInfo *queries.GithubUserInfo) (*db.User, error) {207+func updateUser(a *server.App, accessToken, browserInfo string, userInfo *queries.GithubUserInfo) (*db.User, error) {
204 user, err := queries.UpdateUser(a, accessToken, browserInfo, userInfo)208 user, err := queries.UpdateUser(a, accessToken, browserInfo, userInfo)
205 if err != nil {209 if err != nil {
206 return nil, fmt.Errorf("could not update user: %w", err)210 return nil, fmt.Errorf("could not update user: %w", err)
@@ -254,7 +258,7 @@ func fetchGithubAPI(url string, authHeader string, result interface{}) error {
254 }258 }
255 259
256 // githubGetUserDetails gets the user details from the Github API using the access token260 // githubGetUserDetails gets the user details from the Github API using the access token
257-func githubGetUserDetails(c echo.Context, a *app.App) (userInfo *queries.GithubUserInfo, err error) {261+func githubGetUserDetails(c echo.Context, a *server.App) (userInfo *queries.GithubUserInfo, err error) {
258 accessToken := c.QueryParam("access_token")262 accessToken := c.QueryParam("access_token")
259 263
260 // Fetch user info264 // Fetch user info
M internal/httpserve/handler/static.go +2 -2
@@ -4,12 +4,12 @@ import (
44 "net/http"
55 "os"
66
7- "github.com/bnema/gordon/internal/app"
7+ "github.com/bnema/gordon/internal/server"
88 "github.com/labstack/echo/v4"
99 )
1010
1111 // StaticRoute serves static files from the embedded filesystem
12-func StaticRoute(c echo.Context, a *app.App) error {
12+func StaticRoute(c echo.Context, a *server.App) error {
1313 // Set the cache-control header based on PROD environment variable
1414 if os.Getenv("PROD") == "true" {
1515 c.Response().Header().Set("Cache-Control", "public, max-age=86400")
@@ -4,12 +4,12 @@ import (
4 "net/http"4 "net/http"
5 "os"5 "os"
6 6
7- "github.com/bnema/gordon/internal/app"7+ "github.com/bnema/gordon/internal/server"
8 "github.com/labstack/echo/v4"8 "github.com/labstack/echo/v4"
9 )9 )
10 10
11 // StaticRoute serves static files from the embedded filesystem11 // StaticRoute serves static files from the embedded filesystem
12-func StaticRoute(c echo.Context, a *app.App) error {12+func StaticRoute(c echo.Context, a *server.App) error {
13 // Set the cache-control header based on PROD environment variable13 // Set the cache-control header based on PROD environment variable
14 if os.Getenv("PROD") == "true" {14 if os.Getenv("PROD") == "true" {
15 c.Response().Header().Set("Cache-Control", "public, max-age=86400")15 c.Response().Header().Set("Cache-Control", "public, max-age=86400")
M internal/httpserve/handler/uploadcontainerimage.go +3 -3
@@ -5,7 +5,7 @@ import (
55 "io"
66 "net/http"
77
8- "github.com/bnema/gordon/internal/app"
8+ "github.com/bnema/gordon/internal/server"
99 "github.com/bnema/gordon/internal/templating/render"
1010 "github.com/bnema/gordon/pkg/store"
1111 "github.com/labstack/echo/v4"
@@ -14,7 +14,7 @@ import (
1414 const MaxUploadSize = 1024 * 1024 * 1024 // 1GB
1515
1616 // UploadImageHandler handles the /upload-image route to show the form
17-func UploadImageGETHandler(c echo.Context, a *app.App) error {
17+func UploadImageGETHandler(c echo.Context, a *server.App) error {
1818 data := map[string]interface{}{
1919 "Title": "Upload Image",
2020 }
@@ -32,7 +32,7 @@ func UploadImageGETHandler(c echo.Context, a *app.App) error {
3232 }
3333
3434 // UploadImageHandler handles the /upload-image
35-func UploadImagePOSTHandler(c echo.Context, a *app.App) error {
35+func UploadImagePOSTHandler(c echo.Context, a *server.App) error {
3636 // Set upload size limit
3737 c.Request().Body = http.MaxBytesReader(c.Response(), c.Request().Body, MaxUploadSize)
3838 if err := c.Request().ParseMultipartForm(MaxUploadSize); err != nil {
@@ -5,7 +5,7 @@ import (
5 "io"5 "io"
6 "net/http"6 "net/http"
7 7
8- "github.com/bnema/gordon/internal/app"8+ "github.com/bnema/gordon/internal/server"
9 "github.com/bnema/gordon/internal/templating/render"9 "github.com/bnema/gordon/internal/templating/render"
10 "github.com/bnema/gordon/pkg/store"10 "github.com/bnema/gordon/pkg/store"
11 "github.com/labstack/echo/v4"11 "github.com/labstack/echo/v4"
@@ -14,7 +14,7 @@ import (
14 const MaxUploadSize = 1024 * 1024 * 1024 // 1GB14 const MaxUploadSize = 1024 * 1024 * 1024 // 1GB
15 15
16 // UploadImageHandler handles the /upload-image route to show the form16 // UploadImageHandler handles the /upload-image route to show the form
17-func UploadImageGETHandler(c echo.Context, a *app.App) error {17+func UploadImageGETHandler(c echo.Context, a *server.App) error {
18 data := map[string]interface{}{18 data := map[string]interface{}{
19 "Title": "Upload Image",19 "Title": "Upload Image",
20 }20 }
@@ -32,7 +32,7 @@ func UploadImageGETHandler(c echo.Context, a *app.App) error {
32 }32 }
33 33
34 // UploadImageHandler handles the /upload-image34 // UploadImageHandler handles the /upload-image
35-func UploadImagePOSTHandler(c echo.Context, a *app.App) error {35+func UploadImagePOSTHandler(c echo.Context, a *server.App) error {
36 // Set upload size limit36 // Set upload size limit
37 c.Request().Body = http.MaxBytesReader(c.Response(), c.Request().Body, MaxUploadSize)37 c.Request().Body = http.MaxBytesReader(c.Response(), c.Request().Body, MaxUploadSize)
38 if err := c.Request().ParseMultipartForm(MaxUploadSize); err != nil {38 if err := c.Request().ParseMultipartForm(MaxUploadSize); err != nil {
M internal/httpserve/middleware/commondata.go +2 -2
@@ -1,11 +1,11 @@
11 package middleware
22
33 import (
4- "github.com/bnema/gordon/internal/app"
4+ "github.com/bnema/gordon/internal/server"
55 "github.com/labstack/echo/v4"
66 )
77
8-func SetCommonDataMiddleware(a *app.App) echo.MiddlewareFunc {
8+func SetCommonDataMiddleware(a *server.App) echo.MiddlewareFunc {
99 return func(next echo.HandlerFunc) echo.HandlerFunc {
1010 return func(c echo.Context) error {
1111 // TODO: set common data
@@ -1,11 +1,11 @@
1 package middleware1 package middleware
2 2
3 import (3 import (
4- "github.com/bnema/gordon/internal/app"4+ "github.com/bnema/gordon/internal/server"
5 "github.com/labstack/echo/v4"5 "github.com/labstack/echo/v4"
6 )6 )
7 7
8-func SetCommonDataMiddleware(a *app.App) echo.MiddlewareFunc {8+func SetCommonDataMiddleware(a *server.App) echo.MiddlewareFunc {
9 return func(next echo.HandlerFunc) echo.HandlerFunc {9 return func(next echo.HandlerFunc) echo.HandlerFunc {
10 return func(c echo.Context) error {10 return func(c echo.Context) error {
11 // TODO: set common data11 // TODO: set common data
M internal/httpserve/middleware/requirelogin.go +6 -6
@@ -6,15 +6,15 @@ import (
66 "net/http"
77 "time"
88
9- "github.com/bnema/gordon/internal/app"
109 "github.com/bnema/gordon/internal/db/queries"
10+ "github.com/bnema/gordon/internal/server"
1111
1212 // "github.com/labstack/echo-contrib/session"
1313 "github.com/labstack/echo-contrib/session"
1414 "github.com/labstack/echo/v4"
1515 )
1616
17-func RequireLogin(a *app.App) echo.MiddlewareFunc {
17+func RequireLogin(a *server.App) echo.MiddlewareFunc {
1818 return func(next echo.HandlerFunc) echo.HandlerFunc {
1919 return func(c echo.Context) error {
2020 if err := validateSessionAndUser(c, a); err != nil {
@@ -26,7 +26,7 @@ func RequireLogin(a *app.App) echo.MiddlewareFunc {
2626 }
2727 }
2828
29-func validateSessionAndUser(c echo.Context, a *app.App) error {
29+func validateSessionAndUser(c echo.Context, a *server.App) error {
3030 sess, err := session.Get("session", c)
3131 if err != nil {
3232 return err
@@ -59,7 +59,7 @@ func validateSessionAndUser(c echo.Context, a *app.App) error {
5959 return nil
6060 }
6161
62-func redirectToLogin(c echo.Context, a *app.App) error {
62+func redirectToLogin(c echo.Context, a *server.App) error {
6363 return c.Redirect(http.StatusSeeOther, a.Config.Admin.Path+"/login")
6464 }
6565
@@ -74,7 +74,7 @@ func isCookieExpired(c echo.Context) (bool, error) {
7474 return time.Now().After(cookie.Expires), nil
7575 }
7676
77-func isSessionExpiredInDB(a *app.App, userID string, sessionID string) (bool, error) {
77+func isSessionExpiredInDB(a *server.App, userID string, sessionID string) (bool, error) {
7878 currentTime := time.Now()
7979 expirationTime, err := queries.GetSessionExpiration(a, userID, sessionID, currentTime)
8080 if err != nil {
@@ -84,7 +84,7 @@ func isSessionExpiredInDB(a *app.App, userID string, sessionID string) (bool, er
8484 return currentTime.After(expirationTime), nil
8585 }
8686
87-func isAccountIDInDB(a *app.App, accountID string) (bool, error) {
87+func isAccountIDInDB(a *server.App, accountID string) (bool, error) {
8888 accountExists, err := queries.CheckDBAccountExists(a, accountID)
8989 if err != nil {
9090 return false, err
@@ -6,15 +6,15 @@ import (
6 "net/http"6 "net/http"
7 "time"7 "time"
8 8
9- "github.com/bnema/gordon/internal/app"
10 "github.com/bnema/gordon/internal/db/queries"9 "github.com/bnema/gordon/internal/db/queries"
10+ "github.com/bnema/gordon/internal/server"
11 11
12 // "github.com/labstack/echo-contrib/session"12 // "github.com/labstack/echo-contrib/session"
13 "github.com/labstack/echo-contrib/session"13 "github.com/labstack/echo-contrib/session"
14 "github.com/labstack/echo/v4"14 "github.com/labstack/echo/v4"
15 )15 )
16 16
17-func RequireLogin(a *app.App) echo.MiddlewareFunc {17+func RequireLogin(a *server.App) echo.MiddlewareFunc {
18 return func(next echo.HandlerFunc) echo.HandlerFunc {18 return func(next echo.HandlerFunc) echo.HandlerFunc {
19 return func(c echo.Context) error {19 return func(c echo.Context) error {
20 if err := validateSessionAndUser(c, a); err != nil {20 if err := validateSessionAndUser(c, a); err != nil {
@@ -26,7 +26,7 @@ func RequireLogin(a *app.App) echo.MiddlewareFunc {
26 }26 }
27 }27 }
28 28
29-func validateSessionAndUser(c echo.Context, a *app.App) error {29+func validateSessionAndUser(c echo.Context, a *server.App) error {
30 sess, err := session.Get("session", c)30 sess, err := session.Get("session", c)
31 if err != nil {31 if err != nil {
32 return err32 return err
@@ -59,7 +59,7 @@ func validateSessionAndUser(c echo.Context, a *app.App) error {
59 return nil59 return nil
60 }60 }
61 61
62-func redirectToLogin(c echo.Context, a *app.App) error {62+func redirectToLogin(c echo.Context, a *server.App) error {
63 return c.Redirect(http.StatusSeeOther, a.Config.Admin.Path+"/login")63 return c.Redirect(http.StatusSeeOther, a.Config.Admin.Path+"/login")
64 }64 }
65 65
@@ -74,7 +74,7 @@ func isCookieExpired(c echo.Context) (bool, error) {
74 return time.Now().After(cookie.Expires), nil74 return time.Now().After(cookie.Expires), nil
75 }75 }
76 76
77-func isSessionExpiredInDB(a *app.App, userID string, sessionID string) (bool, error) {77+func isSessionExpiredInDB(a *server.App, userID string, sessionID string) (bool, error) {
78 currentTime := time.Now()78 currentTime := time.Now()
79 expirationTime, err := queries.GetSessionExpiration(a, userID, sessionID, currentTime)79 expirationTime, err := queries.GetSessionExpiration(a, userID, sessionID, currentTime)
80 if err != nil {80 if err != nil {
@@ -84,7 +84,7 @@ func isSessionExpiredInDB(a *app.App, userID string, sessionID string) (bool, er
84 return currentTime.After(expirationTime), nil84 return currentTime.After(expirationTime), nil
85 }85 }
86 86
87-func isAccountIDInDB(a *app.App, accountID string) (bool, error) {87+func isAccountIDInDB(a *server.App, accountID string) (bool, error) {
88 accountExists, err := queries.CheckDBAccountExists(a, accountID)88 accountExists, err := queries.CheckDBAccountExists(a, accountID)
89 if err != nil {89 if err != nil {
90 return false, err90 return false, err
M internal/httpserve/middleware/requiretoken.go +3 -3
@@ -4,12 +4,12 @@ import (
44 "fmt"
55 "strings"
66
7- "github.com/bnema/gordon/internal/app"
7+ "github.com/bnema/gordon/internal/server"
88 "github.com/labstack/echo/v4"
99 )
1010
1111 // RequireToken is a middleware that checks for a valid token in the request
12-func RequireToken(a *app.App) echo.MiddlewareFunc {
12+func RequireToken(a *server.App) echo.MiddlewareFunc {
1313 return func(next echo.HandlerFunc) echo.HandlerFunc {
1414 return func(c echo.Context) error {
1515 if err := validateToken(c, a); err != nil {
@@ -20,7 +20,7 @@ func RequireToken(a *app.App) echo.MiddlewareFunc {
2020 }
2121 }
2222
23-func validateToken(c echo.Context, a *app.App) error {
23+func validateToken(c echo.Context, a *server.App) error {
2424 token := c.Request().Header.Get("Authorization")
2525 if token == "" {
2626 return echo.ErrUnauthorized
@@ -4,12 +4,12 @@ import (
4 "fmt"4 "fmt"
5 "strings"5 "strings"
6 6
7- "github.com/bnema/gordon/internal/app"7+ "github.com/bnema/gordon/internal/server"
8 "github.com/labstack/echo/v4"8 "github.com/labstack/echo/v4"
9 )9 )
10 10
11 // RequireToken is a middleware that checks for a valid token in the request11 // RequireToken is a middleware that checks for a valid token in the request
12-func RequireToken(a *app.App) echo.MiddlewareFunc {12+func RequireToken(a *server.App) echo.MiddlewareFunc {
13 return func(next echo.HandlerFunc) echo.HandlerFunc {13 return func(next echo.HandlerFunc) echo.HandlerFunc {
14 return func(c echo.Context) error {14 return func(c echo.Context) error {
15 if err := validateToken(c, a); err != nil {15 if err := validateToken(c, a); err != nil {
@@ -20,7 +20,7 @@ func RequireToken(a *app.App) echo.MiddlewareFunc {
20 }20 }
21 }21 }
22 22
23-func validateToken(c echo.Context, a *app.App) error {23+func validateToken(c echo.Context, a *server.App) error {
24 token := c.Request().Header.Get("Authorization")24 token := c.Request().Header.Get("Authorization")
25 if token == "" {25 if token == "" {
26 return echo.ErrUnauthorized26 return echo.ErrUnauthorized
M internal/httpserve/router.go +7 -7
@@ -1,15 +1,15 @@
11 package httpserve
22
33 import (
4- "github.com/bnema/gordon/internal/app"
54 "github.com/bnema/gordon/internal/httpserve/handler"
65 "github.com/bnema/gordon/internal/httpserve/middleware"
6+ "github.com/bnema/gordon/internal/server"
77 _ "github.com/joho/godotenv/autoload"
88 "github.com/labstack/echo/v4"
99 )
1010
1111 // RegisterRoutes registers all routes for the application
12-func RegisterRoutes(e *echo.Echo, a *app.App) *echo.Echo {
12+func RegisterRoutes(e *echo.Echo, a *server.App) *echo.Echo {
1313 // --- Register API endpoints --- //
1414 bindAPIEndpoints(e, a)
1515 AdminPath := a.Config.Admin.Path
@@ -42,7 +42,7 @@ func RegisterRoutes(e *echo.Echo, a *app.App) *echo.Echo {
4242 }
4343
4444 // bindAPIEndpoints expose /api endpoints and speaks only JSON
45-func bindAPIEndpoints(e *echo.Echo, a *app.App) {
45+func bindAPIEndpoints(e *echo.Echo, a *server.App) {
4646 apiGroup := e.Group("/api")
4747 apiGroup.Use(middleware.RequireToken(a))
4848 apiGroup.GET("/hello", func(c echo.Context) error {
@@ -54,14 +54,14 @@ func bindAPIEndpoints(e *echo.Echo, a *app.App) {
5454 }
5555
5656 // bindStaticRoute bind static path
57-func bindStaticRoute(e *echo.Echo, a *app.App, path string) {
57+func bindStaticRoute(e *echo.Echo, a *server.App, path string) {
5858 e.GET(path, func(c echo.Context) error {
5959 return handler.StaticRoute(c, a)
6060 })
6161 }
6262
6363 // bindLoginRoute binds all login routes
64-func bindLoginRoute(e *echo.Echo, a *app.App, adminPath string) {
64+func bindLoginRoute(e *echo.Echo, a *server.App, adminPath string) {
6565 e.GET(adminPath+"/login", func(c echo.Context) error {
6666 return handler.RenderLoginPage(c, a)
6767 })
@@ -77,7 +77,7 @@ func bindLoginRoute(e *echo.Echo, a *app.App, adminPath string) {
7777 }
7878
7979 // bindAdminRoute binds all admin routes
80-func bindAdminRoute(e *echo.Echo, a *app.App, adminPath string) {
80+func bindAdminRoute(e *echo.Echo, a *server.App, adminPath string) {
8181 adminGroup := e.Group(adminPath)
8282 // Since login is behind the admin path, we cannot use group middleware
8383 adminGroup.GET("", func(c echo.Context) error {
@@ -90,7 +90,7 @@ func bindAdminRoute(e *echo.Echo, a *app.App, adminPath string) {
9090 }
9191
9292 // bindHTMXEndpoints binds all HTMX endpoints
93-func bindHTMXEndpoints(e *echo.Echo, a *app.App) {
93+func bindHTMXEndpoints(e *echo.Echo, a *server.App) {
9494 // Create a group for /htmx endpoints
9595 htmxGroup := e.Group("/htmx")
9696
@@ -1,15 +1,15 @@
1 package httpserve1 package httpserve
2 2
3 import (3 import (
4- "github.com/bnema/gordon/internal/app"
5 "github.com/bnema/gordon/internal/httpserve/handler"4 "github.com/bnema/gordon/internal/httpserve/handler"
6 "github.com/bnema/gordon/internal/httpserve/middleware"5 "github.com/bnema/gordon/internal/httpserve/middleware"
6+ "github.com/bnema/gordon/internal/server"
7 _ "github.com/joho/godotenv/autoload"7 _ "github.com/joho/godotenv/autoload"
8 "github.com/labstack/echo/v4"8 "github.com/labstack/echo/v4"
9 )9 )
10 10
11 // RegisterRoutes registers all routes for the application11 // RegisterRoutes registers all routes for the application
12-func RegisterRoutes(e *echo.Echo, a *app.App) *echo.Echo {12+func RegisterRoutes(e *echo.Echo, a *server.App) *echo.Echo {
13 // --- Register API endpoints --- //13 // --- Register API endpoints --- //
14 bindAPIEndpoints(e, a)14 bindAPIEndpoints(e, a)
15 AdminPath := a.Config.Admin.Path15 AdminPath := a.Config.Admin.Path
@@ -42,7 +42,7 @@ func RegisterRoutes(e *echo.Echo, a *app.App) *echo.Echo {
42 }42 }
43 43
44 // bindAPIEndpoints expose /api endpoints and speaks only JSON44 // bindAPIEndpoints expose /api endpoints and speaks only JSON
45-func bindAPIEndpoints(e *echo.Echo, a *app.App) {45+func bindAPIEndpoints(e *echo.Echo, a *server.App) {
46 apiGroup := e.Group("/api")46 apiGroup := e.Group("/api")
47 apiGroup.Use(middleware.RequireToken(a))47 apiGroup.Use(middleware.RequireToken(a))
48 apiGroup.GET("/hello", func(c echo.Context) error {48 apiGroup.GET("/hello", func(c echo.Context) error {
@@ -54,14 +54,14 @@ func bindAPIEndpoints(e *echo.Echo, a *app.App) {
54 }54 }
55 55
56 // bindStaticRoute bind static path56 // bindStaticRoute bind static path
57-func bindStaticRoute(e *echo.Echo, a *app.App, path string) {57+func bindStaticRoute(e *echo.Echo, a *server.App, path string) {
58 e.GET(path, func(c echo.Context) error {58 e.GET(path, func(c echo.Context) error {
59 return handler.StaticRoute(c, a)59 return handler.StaticRoute(c, a)
60 })60 })
61 }61 }
62 62
63 // bindLoginRoute binds all login routes63 // bindLoginRoute binds all login routes
64-func bindLoginRoute(e *echo.Echo, a *app.App, adminPath string) {64+func bindLoginRoute(e *echo.Echo, a *server.App, adminPath string) {
65 e.GET(adminPath+"/login", func(c echo.Context) error {65 e.GET(adminPath+"/login", func(c echo.Context) error {
66 return handler.RenderLoginPage(c, a)66 return handler.RenderLoginPage(c, a)
67 })67 })
@@ -77,7 +77,7 @@ func bindLoginRoute(e *echo.Echo, a *app.App, adminPath string) {
77 }77 }
78 78
79 // bindAdminRoute binds all admin routes79 // bindAdminRoute binds all admin routes
80-func bindAdminRoute(e *echo.Echo, a *app.App, adminPath string) {80+func bindAdminRoute(e *echo.Echo, a *server.App, adminPath string) {
81 adminGroup := e.Group(adminPath)81 adminGroup := e.Group(adminPath)
82 // Since login is behind the admin path, we cannot use group middleware82 // Since login is behind the admin path, we cannot use group middleware
83 adminGroup.GET("", func(c echo.Context) error {83 adminGroup.GET("", func(c echo.Context) error {
@@ -90,7 +90,7 @@ func bindAdminRoute(e *echo.Echo, a *app.App, adminPath string) {
90 }90 }
91 91
92 // bindHTMXEndpoints binds all HTMX endpoints92 // bindHTMXEndpoints binds all HTMX endpoints
93-func bindHTMXEndpoints(e *echo.Echo, a *app.App) {93+func bindHTMXEndpoints(e *echo.Echo, a *server.App) {
94 // Create a group for /htmx endpoints94 // Create a group for /htmx endpoints
95 htmxGroup := e.Group("/htmx")95 htmxGroup := e.Group("/htmx")
96 96
R internal/app/app.go → internal/server/appserver.go +3 -3 renamed, 98% similar
@@ -1,4 +1,4 @@
1-package app
1+package server
22
33 import (
44 "database/sql"
@@ -42,7 +42,7 @@ type GeneralConfig struct {
4242 BuildDir string // come from env
4343 BuildVersion string // come from env
4444 StorageDir string `yaml:"storageDir"` // = buildir/storage
45- GordonToken string `yaml:"gordonToken"`
45+ Token string `yaml:"token"`
4646 }
4747
4848 type HttpConfig struct {
@@ -167,7 +167,7 @@ func (config *Config) UpdateConfig() error {
167167 }
168168
169169 func (config *Config) GetToken() (string, error) {
170- token := config.General.GordonToken
170+ token := config.General.Token
171171 if token == "" {
172172 return "", fmt.Errorf("no token found in config.yml")
173173 }
@@ -1,4 +1,4 @@
1-package app1+package server
2 2
3 import (3 import (
4 "database/sql"4 "database/sql"
@@ -42,7 +42,7 @@ type GeneralConfig struct {
42 BuildDir string // come from env42 BuildDir string // come from env
43 BuildVersion string // come from env43 BuildVersion string // come from env
44 StorageDir string `yaml:"storageDir"` // = buildir/storage44 StorageDir string `yaml:"storageDir"` // = buildir/storage
45- GordonToken string `yaml:"gordonToken"`45+ Token string `yaml:"token"`
46 }46 }
47 47
48 type HttpConfig struct {48 type HttpConfig struct {
@@ -167,7 +167,7 @@ func (config *Config) UpdateConfig() error {
167 }167 }
168 168
169 func (config *Config) GetToken() (string, error) {169 func (config *Config) GetToken() (string, error) {
170- token := config.General.GordonToken170+ token := config.General.Token
171 if token == "" {171 if token == "" {
172 return "", fmt.Errorf("no token found in config.yml")172 return "", fmt.Errorf("no token found in config.yml")
173 }173 }
R internal/app/newserver.go → internal/server/newserver.go +2 -1 renamed, 98% similar
@@ -1,4 +1,4 @@
1-package app
1+package server
22
33 import (
44 "fmt"
@@ -17,6 +17,7 @@ func NewServerApp() *App {
1717 if err != nil {
1818 log.Fatalf("Failed to load configuration: %v", err)
1919 }
20+
2021 // Append build dir to storage dir
2122 config.General.StorageDir = fmt.Sprintf("%s/%s", config.General.BuildDir, config.General.StorageDir)
2223
@@ -1,4 +1,4 @@
1-package app1+package server
2 2
3 import (3 import (
4 "fmt"4 "fmt"
@@ -17,6 +17,7 @@ func NewServerApp() *App {
17 if err != nil {17 if err != nil {
18 log.Fatalf("Failed to load configuration: %v", err)18 log.Fatalf("Failed to load configuration: %v", err)
19 }19 }
20+
20 // Append build dir to storage dir21 // Append build dir to storage dir
21 config.General.StorageDir = fmt.Sprintf("%s/%s", config.General.BuildDir, config.General.StorageDir)22 config.General.StorageDir = fmt.Sprintf("%s/%s", config.General.BuildDir, config.General.StorageDir)
22 23
R internal/app/sqliteclose.go → internal/server/sqliteclose.go +1 -1 renamed, 95% similar
@@ -1,4 +1,4 @@
1-package app
1+package server
22
33 // CloseAndSaveDB closes the in-memory database and backup the database file if there is any modification.
44 func CloseDB(a *App) error {
@@ -1,4 +1,4 @@
1-package app1+package server
2 2
3 // CloseAndSaveDB closes the in-memory database and backup the database file if there is any modification.3 // CloseAndSaveDB closes the in-memory database and backup the database file if there is any modification.
4 func CloseDB(a *App) error {4 func CloseDB(a *App) error {
R internal/app/sqliteinit.go → internal/server/sqliteinit.go +1 -1 renamed, 99% similar
@@ -1,4 +1,4 @@
1-package app
1+package server
22
33 import (
44 "database/sql"
@@ -1,4 +1,4 @@
1-package app1+package server
2 2
3 import (3 import (
4 "database/sql"4 "database/sql"
R internal/app/tokeninit.go → internal/server/tokeninit.go +2 -2 renamed, 96% similar
@@ -1,4 +1,4 @@
1-package app
1+package server
22
33 import (
44 "crypto/rand"
@@ -32,7 +32,7 @@ func HandleNewTokenInitialization(a *App) (string, error) {
3232 fmt.Printf("Login with the new token: %s\n", token)
3333
3434 // Store the token in the config file
35- a.Config.General.GordonToken = token
35+ a.Config.General.Token = token
3636 err = a.Config.UpdateConfig()
3737 if err != nil {
3838 return "", fmt.Errorf("failed to save config: %v", err)
@@ -1,4 +1,4 @@
1-package app1+package server
2 2
3 import (3 import (
4 "crypto/rand"4 "crypto/rand"
@@ -32,7 +32,7 @@ func HandleNewTokenInitialization(a *App) (string, error) {
32 fmt.Printf("Login with the new token: %s\n", token)32 fmt.Printf("Login with the new token: %s\n", token)
33 33
34 // Store the token in the config file34 // Store the token in the config file
35- a.Config.General.GordonToken = token35+ a.Config.General.Token = token
36 err = a.Config.UpdateConfig()36 err = a.Config.UpdateConfig()
37 if err != nil {37 if err != nil {
38 return "", fmt.Errorf("failed to save config: %v", err)38 return "", fmt.Errorf("failed to save config: %v", err)
M internal/templating/load/loadfragment.go +2 -2
@@ -4,11 +4,11 @@ import (
44 "fmt"
55 "io"
66
7- "github.com/bnema/gordon/internal/app"
7+ "github.com/bnema/gordon/internal/server"
88 )
99
1010 // LoadFragment loads a specific HTML fragment from the app's TemplateFS
11-func Fragment(a *app.App, fragmentName string) (string, error) {
11+func Fragment(a *server.App, fragmentName string) (string, error) {
1212 filePath := fmt.Sprintf("html/fragments/%s.gohtml", fragmentName)
1313
1414 // Open the file
@@ -4,11 +4,11 @@ import (
4 "fmt"4 "fmt"
5 "io"5 "io"
6 6
7- "github.com/bnema/gordon/internal/app"7+ "github.com/bnema/gordon/internal/server"
8 )8 )
9 9
10 // LoadFragment loads a specific HTML fragment from the app's TemplateFS10 // LoadFragment loads a specific HTML fragment from the app's TemplateFS
11-func Fragment(a *app.App, fragmentName string) (string, error) {11+func Fragment(a *server.App, fragmentName string) (string, error) {
12 filePath := fmt.Sprintf("html/fragments/%s.gohtml", fragmentName)12 filePath := fmt.Sprintf("html/fragments/%s.gohtml", fragmentName)
13 13
14 // Open the file14 // Open the file
M internal/templating/render/cmdparams.go +2 -2
@@ -4,12 +4,12 @@ import (
44 "fmt"
55 "strings"
66
7- "github.com/bnema/gordon/internal/app"
7+ "github.com/bnema/gordon/internal/server"
88 "github.com/bnema/gordon/pkg/docker"
99 )
1010
1111 // FromInputsToCmdParams transforms the inputs map into a ContainerCommandParams struct
12-func FromInputsToCmdParams(inputs map[string]string, a *app.App) (docker.ContainerCommandParams, error) {
12+func FromInputsToCmdParams(inputs map[string]string, a *server.App) (docker.ContainerCommandParams, error) {
1313 volumeStr := inputs["volumes"]
1414 volumeSlice := strings.Split(volumeStr, ",")
1515
@@ -4,12 +4,12 @@ import (
4 "fmt"4 "fmt"
5 "strings"5 "strings"
6 6
7- "github.com/bnema/gordon/internal/app"7+ "github.com/bnema/gordon/internal/server"
8 "github.com/bnema/gordon/pkg/docker"8 "github.com/bnema/gordon/pkg/docker"
9 )9 )
10 10
11 // FromInputsToCmdParams transforms the inputs map into a ContainerCommandParams struct11 // FromInputsToCmdParams transforms the inputs map into a ContainerCommandParams struct
12-func FromInputsToCmdParams(inputs map[string]string, a *app.App) (docker.ContainerCommandParams, error) {12+func FromInputsToCmdParams(inputs map[string]string, a *server.App) (docker.ContainerCommandParams, error) {
13 volumeStr := inputs["volumes"]13 volumeStr := inputs["volumes"]
14 volumeSlice := strings.Split(volumeStr, ",")14 volumeSlice := strings.Split(volumeStr, ",")
15 15
M internal/templating/render/html.go +3 -3
@@ -7,7 +7,7 @@ import (
77 "io/fs"
88 "path"
99
10- "github.com/bnema/gordon/internal/app"
10+ "github.com/bnema/gordon/internal/server"
1111 )
1212
1313 type Renderer struct {
@@ -17,7 +17,7 @@ type Renderer struct {
1717 }
1818
1919 // Render function renders the template with the given data
20-func (r *Renderer) Render(data interface{}, a *app.App) (string, error) {
20+func (r *Renderer) Render(data interface{}, a *server.App) (string, error) {
2121 if r.ParseError != nil {
2222 return "", fmt.Errorf("failed to parse template: %w", r.ParseError)
2323
@@ -43,7 +43,7 @@ func (r *Renderer) Render(data interface{}, a *app.App) (string, error) {
4343 }
4444
4545 // GetHTMLRenderer function returns a new Renderer instance
46-func GetHTMLRenderer(mainPath string, filename string, fs fs.FS, a *app.App, fragmentsPath ...string) (*Renderer, error) {
46+func GetHTMLRenderer(mainPath string, filename string, fs fs.FS, a *server.App, fragmentsPath ...string) (*Renderer, error) {
4747 // Full path to the main template
4848 fullPath := path.Join(mainPath, filename)
4949 // Check if the file exists in the provided fs.FS using fs.Open
@@ -7,7 +7,7 @@ import (
7 "io/fs"7 "io/fs"
8 "path"8 "path"
9 9
10- "github.com/bnema/gordon/internal/app"10+ "github.com/bnema/gordon/internal/server"
11 )11 )
12 12
13 type Renderer struct {13 type Renderer struct {
@@ -17,7 +17,7 @@ type Renderer struct {
17 }17 }
18 18
19 // Render function renders the template with the given data19 // Render function renders the template with the given data
20-func (r *Renderer) Render(data interface{}, a *app.App) (string, error) {20+func (r *Renderer) Render(data interface{}, a *server.App) (string, error) {
21 if r.ParseError != nil {21 if r.ParseError != nil {
22 return "", fmt.Errorf("failed to parse template: %w", r.ParseError)22 return "", fmt.Errorf("failed to parse template: %w", r.ParseError)
23 23
@@ -43,7 +43,7 @@ func (r *Renderer) Render(data interface{}, a *app.App) (string, error) {
43 }43 }
44 44
45 // GetHTMLRenderer function returns a new Renderer instance45 // GetHTMLRenderer function returns a new Renderer instance
46-func GetHTMLRenderer(mainPath string, filename string, fs fs.FS, a *app.App, fragmentsPath ...string) (*Renderer, error) {46+func GetHTMLRenderer(mainPath string, filename string, fs fs.FS, a *server.App, fragmentsPath ...string) (*Renderer, error) {
47 // Full path to the main template47 // Full path to the main template
48 fullPath := path.Join(mainPath, filename)48 fullPath := path.Join(mainPath, filename)
49 // Check if the file exists in the provided fs.FS using fs.Open49 // Check if the file exists in the provided fs.FS using fs.Open
M internal/templating/render/localization.go +3 -3
@@ -3,14 +3,14 @@ package render
33 import (
44 "fmt"
55
6- "github.com/bnema/gordon/internal/app"
6+ "github.com/bnema/gordon/internal/server"
77 "gopkg.in/yaml.v3"
88 )
99
1010 type Localizations map[string]map[string]map[string]interface{}
1111
1212 // GetLocalization function returns the localization for the given language
13-func GetLocalization(lang string, a *app.App) (map[string]interface{}, error) {
13+func GetLocalization(lang string, a *server.App) (map[string]interface{}, error) {
1414 // 1. Check if the language is supported
1515 supportedLanguages := []string{"en", "fr"} // Add more languages here
1616 if !contains(supportedLanguages, lang) {
@@ -38,7 +38,7 @@ func GetLocalization(lang string, a *app.App) (map[string]interface{}, error) {
3838 }
3939
4040 // getLocalizations function returns the localizations from the strings.yml file
41-func getLocalizations(a *app.App) (Localizations, error) {
41+func getLocalizations(a *server.App) (Localizations, error) {
4242 var loc Localizations
4343
4444 err := yaml.Unmarshal(a.LocYML, &loc)
@@ -3,14 +3,14 @@ package render
3 import (3 import (
4 "fmt"4 "fmt"
5 5
6- "github.com/bnema/gordon/internal/app"6+ "github.com/bnema/gordon/internal/server"
7 "gopkg.in/yaml.v3"7 "gopkg.in/yaml.v3"
8 )8 )
9 9
10 type Localizations map[string]map[string]map[string]interface{}10 type Localizations map[string]map[string]map[string]interface{}
11 11
12 // GetLocalization function returns the localization for the given language12 // GetLocalization function returns the localization for the given language
13-func GetLocalization(lang string, a *app.App) (map[string]interface{}, error) {13+func GetLocalization(lang string, a *server.App) (map[string]interface{}, error) {
14 // 1. Check if the language is supported14 // 1. Check if the language is supported
15 supportedLanguages := []string{"en", "fr"} // Add more languages here15 supportedLanguages := []string{"en", "fr"} // Add more languages here
16 if !contains(supportedLanguages, lang) {16 if !contains(supportedLanguages, lang) {
@@ -38,7 +38,7 @@ func GetLocalization(lang string, a *app.App) (map[string]interface{}, error) {
38 }38 }
39 39
40 // getLocalizations function returns the localizations from the strings.yml file40 // getLocalizations function returns the localizations from the strings.yml file
41-func getLocalizations(a *app.App) (Localizations, error) {41+func getLocalizations(a *server.App) (Localizations, error) {
42 var loc Localizations42 var loc Localizations
43 43
44 err := yaml.Unmarshal(a.LocYML, &loc)44 err := yaml.Unmarshal(a.LocYML, &loc)
M pkg/htmx/htmlfragments.go +2 -2
@@ -5,12 +5,12 @@ import (
55 "fmt"
66
77 "github.com/PuerkitoBio/goquery"
8- "github.com/bnema/gordon/internal/app"
8+ "github.com/bnema/gordon/internal/server"
99 "github.com/bnema/gordon/internal/templating/render"
1010 )
1111
1212 // GetHTMLFragmentByID returns the HTML fragment with the specified id
13-func GetHTMLFragmentByID(id string, data interface{}, a *app.App) (string, error) {
13+func GetHTMLFragmentByID(id string, data interface{}, a *server.App) (string, error) {
1414 // 1. Render the template
1515 renderer, err := render.GetHTMLRenderer("html/fragments", "components.gohtml", a.TemplateFS, a)
1616 if err != nil {
@@ -5,12 +5,12 @@ import (
5 "fmt"5 "fmt"
6 6
7 "github.com/PuerkitoBio/goquery"7 "github.com/PuerkitoBio/goquery"
8- "github.com/bnema/gordon/internal/app"8+ "github.com/bnema/gordon/internal/server"
9 "github.com/bnema/gordon/internal/templating/render"9 "github.com/bnema/gordon/internal/templating/render"
10 )10 )
11 11
12 // GetHTMLFragmentByID returns the HTML fragment with the specified id12 // GetHTMLFragmentByID returns the HTML fragment with the specified id
13-func GetHTMLFragmentByID(id string, data interface{}, a *app.App) (string, error) {13+func GetHTMLFragmentByID(id string, data interface{}, a *server.App) (string, error) {
14 // 1. Render the template14 // 1. Render the template
15 renderer, err := render.GetHTMLRenderer("html/fragments", "components.gohtml", a.TemplateFS, a)15 renderer, err := render.GetHTMLRenderer("html/fragments", "components.gohtml", a.TemplateFS, a)
16 if err != nil {16 if err != nil {
M pkg/store/storeimages.go +3 -3
@@ -6,7 +6,7 @@ import (
66 "os"
77 "path/filepath"
88
9- "github.com/bnema/gordon/internal/app"
9+ "github.com/bnema/gordon/internal/server"
1010 "github.com/bnema/gordon/pkg/docker"
1111 "github.com/docker/docker/api/types"
1212 )
@@ -17,13 +17,13 @@ type StorageConfig struct {
1717 Images []types.ImageSummary
1818 }
1919
20-func NewStorageConfig(config *app.Config) *StorageConfig {
20+func NewStorageConfig(config *server.Config) *StorageConfig {
2121 return &StorageConfig{
2222 StorageDir: config.General.StorageDir,
2323 }
2424 }
2525
26-func SaveImageToStorage(config *app.Config, filename string, buf io.Reader) (string, error) {
26+func SaveImageToStorage(config *server.Config, filename string, buf io.Reader) (string, error) {
2727 // Check if the folder exist if not create it
2828 if _, err := os.Stat(config.General.StorageDir); os.IsNotExist(err) {
2929 err := os.MkdirAll(config.General.StorageDir, 0755)
@@ -6,7 +6,7 @@ import (
6 "os"6 "os"
7 "path/filepath"7 "path/filepath"
8 8
9- "github.com/bnema/gordon/internal/app"9+ "github.com/bnema/gordon/internal/server"
10 "github.com/bnema/gordon/pkg/docker"10 "github.com/bnema/gordon/pkg/docker"
11 "github.com/docker/docker/api/types"11 "github.com/docker/docker/api/types"
12 )12 )
@@ -17,13 +17,13 @@ type StorageConfig struct {
17 Images []types.ImageSummary17 Images []types.ImageSummary
18 }18 }
19 19
20-func NewStorageConfig(config *app.Config) *StorageConfig {20+func NewStorageConfig(config *server.Config) *StorageConfig {
21 return &StorageConfig{21 return &StorageConfig{
22 StorageDir: config.General.StorageDir,22 StorageDir: config.General.StorageDir,
23 }23 }
24 }24 }
25 25
26-func SaveImageToStorage(config *app.Config, filename string, buf io.Reader) (string, error) {26+func SaveImageToStorage(config *server.Config, filename string, buf io.Reader) (string, error) {
27 // Check if the folder exist if not create it27 // Check if the folder exist if not create it
28 if _, err := os.Stat(config.General.StorageDir); os.IsNotExist(err) {28 if _, err := os.Stat(config.General.StorageDir); os.IsNotExist(err) {
29 err := os.MkdirAll(config.General.StorageDir, 0755)29 err := os.MkdirAll(config.General.StorageDir, 0755)

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 7

Tags 106

↑↓ moveenter openesc close