mirror of
https://github.com/empayre/fleet.git
synced 2024-11-06 08:55:24 +00:00
8b908f6506
* wip * Add tests and finish implementation * Add proper default for periodicity, changes file, and documentation * Fix tests and add defaults also to new installs * EnableHostUsers should be true if undefined as well * In some cases, periodicity can be zero because of the migrations * Apply defaults when migrating appconfig * Fix lint * lint * Address review comments
55 lines
1.1 KiB
Go
55 lines
1.1 KiB
Go
package server
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"io/ioutil"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/pkg/errors"
|
|
)
|
|
|
|
// GenerateRandomText return a string generated by filling in keySize bytes with
|
|
// random data and then base64 encoding those bytes
|
|
func GenerateRandomText(keySize int) (string, error) {
|
|
key := make([]byte, keySize)
|
|
_, err := rand.Read(key)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return base64.StdEncoding.EncodeToString(key), nil
|
|
}
|
|
|
|
func PostJSONWithTimeout(ctx context.Context, url string, v interface{}) error {
|
|
jsonBytes, err := json.Marshal(v)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
client := &http.Client{Timeout: 30 * time.Second}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer(jsonBytes))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
body, _ := ioutil.ReadAll(resp.Body)
|
|
return errors.Errorf("Error posting to %s: %d. %s", url, resp.StatusCode, string(body))
|
|
}
|
|
|
|
return nil
|
|
}
|