Skip to content

Commit ca81a23

Browse files
committed
Implement Ping() interface
1 parent 76032bf commit ca81a23

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

connection.go

+22
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
package restsql
1616

1717
import (
18+
"context"
1819
"database/sql/driver"
1920
"encoding/json"
2021
"io"
@@ -23,6 +24,7 @@ import (
2324
)
2425

2526
type restsqlConn struct {
27+
client *http.Client
2628
url string
2729
}
2830

@@ -37,6 +39,25 @@ func (rc *restsqlConn) Prepare(query string) (driver.Stmt, error) {
3739
return nil, nil
3840
}
3941

42+
// Ping checks connectivity to the host http server by issuing a HEAD request.
43+
func (rc *restsqlConn) Ping(ctx context.Context) (err error) {
44+
req, err := http.NewRequest("HEAD", rc.url, nil)
45+
if err != nil {
46+
return err
47+
}
48+
49+
resp, err := rc.client.Do(req.WithContext(ctx))
50+
if err != nil {
51+
return err
52+
}
53+
54+
resp.Body.Close()
55+
56+
// Note that we do not particularly care about the response code, as we
57+
// only care about whether the endpoint is responsive or not.
58+
return nil
59+
}
60+
4061
// Query carries out a basic SQL query on a REST API endpoint. This presently
4162
// takes the form of the raw query being appended to the base path.
4263
func (rc *restsqlConn) Query(query string, args []driver.Value) (driver.Rows, error) {
@@ -69,5 +90,6 @@ func (rc *restsqlConn) Query(query string, args []driver.Value) (driver.Rows, er
6990

7091
// Close is stubbed out, but is necessary to satisfy the interface requirements
7192
func (rc *restsqlConn) Close() (err error) {
93+
rc.client = nil
7294
return nil
7395
}

driver.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ package restsql
1919
import (
2020
"database/sql"
2121
"database/sql/driver"
22+
"net/http"
2223
)
2324

2425
// RESTSQLDriver is exported to make the driver directly accessible where
@@ -32,7 +33,10 @@ type RESTSQLDriver struct {
3233
func (d RESTSQLDriver) Open(url string) (driver.Conn, error) {
3334
var err error
3435

35-
rc := &restsqlConn{url: url}
36+
rc := &restsqlConn{
37+
client: http.DefaultClient,
38+
url: url,
39+
}
3640

3741
return rc, err
3842
}

0 commit comments

Comments
 (0)