Initial take on bookmarks

This commit is contained in:
Dan Sosedoff 2014-12-02 22:19:38 -06:00
parent 403701b258
commit 8fae96dcbd
3 changed files with 89 additions and 0 deletions

11
api.go
View File

@ -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",

77
bookmarks.go Normal file
View File

@ -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
}

View File

@ -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...")