Initial commit

This commit is contained in:
2023-02-17 00:26:57 +01:00
commit fa595e6b62
18 changed files with 2793 additions and 0 deletions

24
pkg/util/errors.go Normal file
View File

@@ -0,0 +1,24 @@
package util
import (
"errors"
"net/http"
)
var (
// ErrIPAM indicates an unsupported IPAM driver was used
ErrIPAM = errors.New("only the null IPAM driver is supported")
// ErrNoContainer indicates a container was unexpectedly not found
ErrNoContainer = errors.New("couldn't find container by endpoint on the network")
// ErrGuessFailed indicates that we guessed wrong the container and docker must re-try starting us
ErrGuessFailed = errors.New("guessing of container failed containr must be re-created")
)
func ErrToStatus(err error) int {
switch {
case errors.Is(err, ErrIPAM), errors.Is(err, ErrGuessFailed):
return http.StatusBadRequest
default:
return http.StatusInternalServerError
}
}

15
pkg/util/http.go Normal file
View File

@@ -0,0 +1,15 @@
package util
import (
"io"
"github.com/gorilla/handlers"
log "github.com/sirupsen/logrus"
)
func WriteAccessLog(w io.Writer, params handlers.LogFormatterParams) {
log.WithFields(log.Fields{
"status": params.StatusCode,
"resSize": params.Size,
}).Tracef("%v %v", params.Request.Method, params.URL.RequestURI())
}

61
pkg/util/json.go Normal file
View File

@@ -0,0 +1,61 @@
package util
import (
"encoding/json"
"fmt"
"net/http"
log "github.com/sirupsen/logrus"
)
// JSONResponse Sends a JSON payload in response to a HTTP request
func JSONResponse(w http.ResponseWriter, v interface{}, statusCode int) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
if err := json.NewEncoder(w).Encode(v); err != nil {
log.WithField("err", err).Error("Failed to serialize JSON payload")
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, "Failed to serialize JSON payload")
}
}
type jsonError struct {
Message string `json:"Err"`
}
// JSONErrResponse Sends an `error` as a JSON object with a `message` property
func JSONErrResponse(w http.ResponseWriter, err error, statusCode int) {
log.WithError(err).Error("Error while processing request")
w.Header().Set("Content-Type", "application/problem+json")
if statusCode == 0 {
statusCode = ErrToStatus(err)
}
w.WriteHeader(statusCode)
enc := json.NewEncoder(w)
enc.Encode(jsonError{err.Error()})
}
// ParseJSONBody attempts to parse the request body as JSON
func ParseJSONBody(v interface{}, w http.ResponseWriter, r *http.Request) error {
//data, err := io.ReadAll(r.Body)
//if err != nil {
// JSONErrResponse(w, fmt.Errorf("failed to read request body: %w", err), 0)
// return err
//}
//log.WithField("body", string(data)).Debug("request body")
d := json.NewDecoder(r.Body)
d.DisallowUnknownFields()
if err := d.Decode(v); err != nil {
//if err := json.Unmarshal(data, v); err != nil {
JSONErrResponse(w, fmt.Errorf("failed to parse request body: %w", err), http.StatusBadRequest)
return err
}
return nil
}