Add API method to connect to server with given url

This commit is contained in:
Dan Sosedoff 2014-10-31 22:37:58 -05:00
parent 5a2c13e6c4
commit 7ac9bee098
3 changed files with 41 additions and 0 deletions

30
api.go
View File

@ -34,6 +34,36 @@ func API_Home(c *gin.Context) {
c.Data(200, "text/html; charset=utf-8", data)
}
func API_Connect(c *gin.Context) {
url := c.Request.FormValue("url")
if url == "" {
c.JSON(400, Error{"Url parameter is required"})
return
}
client, err := NewClientFromUrl(url)
if err != nil {
c.JSON(400, Error{err.Error()})
return
}
err = client.Test()
if err != nil {
c.JSON(400, Error{err.Error()})
return
}
info, err := client.Info()
if err == nil {
dbClient.db.Close()
dbClient = client
}
c.JSON(200, info.Format()[0])
}
func API_GetDatabases(c *gin.Context) {
names, err := dbClient.Databases()

View File

@ -32,6 +32,16 @@ func NewClient() (*Client, error) {
return &Client{db: db}, nil
}
func NewClientFromUrl(url string) (*Client, error) {
db, err := sqlx.Open("postgres", url)
if err != nil {
return nil, err
}
return &Client{db: db}, nil
}
func (client *Client) Test() error {
return client.db.Ping()
}

View File

@ -114,6 +114,7 @@ func startServer() {
}
router.GET("/", API_Home)
router.POST("/connect", API_Connect)
router.GET("/databases", API_GetDatabases)
router.GET("/info", API_Info)
router.GET("/tables", API_GetTables)