Skip to content

Commit

Permalink
feat: Add request package and ping function.
Browse files Browse the repository at this point in the history
  • Loading branch information
gowizzard committed Apr 9, 2024
1 parent 4ae949e commit 9845ff0
Show file tree
Hide file tree
Showing 2 changed files with 103 additions and 0 deletions.
75 changes: 75 additions & 0 deletions internal/requests/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// Package request provides the request to the docker socket.
package request

import (
"context"
"net"
"net/http"
"net/url"
"time"
)

// socket is to define the docker socket.
// scheme is to define the scheme for the request.
// host is to define the host for the request.
// timeout is to define the timeout for the request.
// retries is to define the retries for the request.
const (
socket = "/var/run/docker.sock"
scheme = "http"
host = "localhost"
timeout = 5 * time.Second
retries = 3
)

// config is to configure the request.
type config struct {
Path, Method string
Context context.Context
}

// send is to send the request to the docker unix socket.
func (c *config) send() (response *http.Response, err error) {

result := &url.URL{
Scheme: scheme,
Host: host,
Path: c.Path,
}

client := &http.Client{
Transport: &http.Transport{
DialContext: func(context context.Context, network, addr string) (netConn net.Conn, err error) {
if err != nil {
return nil, err
}
return net.DialTimeout("unix", socket, timeout)
},
},
}

request, err := http.NewRequestWithContext(c.Context, c.Method, result.String(), nil)
if err != nil {
return nil, err
}

for i := range retries {

response, err = client.Do(request)
if err != nil {
return nil, err
}

switch response.StatusCode {
case http.StatusTooManyRequests:
time.Sleep(time.Second * time.Duration(2^i))
continue
default:
return response, nil
}

}

return response, nil

}
28 changes: 28 additions & 0 deletions internal/requests/ping.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package request

import (
"context"
"net/http"
)

// Ping is to ping the docker socket and return the status code.
func Ping() (status int, err error) {

ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()

c := config{
Path: "_ping",
Method: http.MethodGet,
Context: ctx,
}

response, err := c.send()
if err != nil {
return 0, err
}
defer response.Body.Close()

return response.StatusCode, nil

}

0 comments on commit 9845ff0

Please sign in to comment.