diff --git a/api.go b/api.go index 9f76dec..728df1c 100644 --- a/api.go +++ b/api.go @@ -198,6 +198,17 @@ func API_HandleQuery(query string, c *gin.Context) { c.JSON(200, result) } +func API_Bookmarks(c *gin.Context) { + bookmarks, err := readAllBookmarks() + + if err != nil { + c.JSON(400, NewError(err)) + return + } + + c.JSON(200, bookmarks) +} + func API_ServeAsset(c *gin.Context) { file := fmt.Sprintf( "static/%s/%s", diff --git a/bookmarks.go b/bookmarks.go new file mode 100644 index 0000000..e6c29f0 --- /dev/null +++ b/bookmarks.go @@ -0,0 +1,77 @@ +package main + +import ( + "fmt" + "io/ioutil" + "path/filepath" + "strings" + + "github.com/BurntSushi/toml" + "github.com/mitchellh/go-homedir" +) + +type Bookmark struct { + Url string `json:"url"` // Postgres connection URL + Host string `json:"host"` // Server hostname + Port int `json:"port"` // Server port + User string `json:"user"` // Database user + Password string `json:"password"` // User password + SslMode string `json:"ssl_mode"` // Connection SSL mode +} + +func readServerConfig(path string) (Bookmark, error) { + bookmark := Bookmark{} + buff, err := ioutil.ReadFile(path) + + if err != nil { + fmt.Println(err) + return bookmark, err + } + + _, err = toml.Decode(string(buff), &bookmark) + + if err != nil { + fmt.Println(err) + } + + return bookmark, err +} + +func fileBasename(path string) string { + filename := filepath.Base(path) + return strings.Replace(filename, filepath.Ext(path), "", 1) +} + +func bookmarksPath() string { + path, _ := homedir.Dir() + return fmt.Sprintf("%s/.pgweb/bookmarks", path) +} + +func readAllBookmarks() (map[string]Bookmark, error) { + path := bookmarksPath() + results := map[string]Bookmark{} + + files, err := ioutil.ReadDir(path) + if err != nil { + return results, err + } + + for _, file := range files { + if filepath.Ext(file.Name()) != ".toml" { + continue + } + + fullPath := path + "/" + file.Name() + key := fileBasename(file.Name()) + config, err := readServerConfig(fullPath) + + if err != nil { + fmt.Println(err) + continue + } + + results[key] = config + } + + return results, nil +} diff --git a/main.go b/main.go index 759f0e7..f1189dd 100644 --- a/main.go +++ b/main.go @@ -161,6 +161,7 @@ func startServer() { router.GET("/explain", API_ExplainQuery) router.POST("/explain", API_ExplainQuery) router.GET("/history", API_History) + router.GET("/bookmarks", API_Bookmarks) router.GET("/static/:type/:name", API_ServeAsset) fmt.Println("Starting server...")