-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathuserdata.go
53 lines (46 loc) · 1.36 KB
/
userdata.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package metadata
import (
"bytes"
"compress/gzip"
"context"
"encoding/base64"
"fmt"
"io"
)
var gzipMagic = []byte{0x1F, 0x8B, 0x08}
// GetUserData returns the user data for the current instance.
// NOTE: The result of this endpoint is automatically decoded from base64 and un-gzipped if needed.
func (c *Client) GetUserData(ctx context.Context) (string, error) {
req := c.R(ctx)
resp, err := coupleAPIErrors(req.Get("user-data"))
if err != nil {
return "", err
}
// user-data is returned as a raw string
decodedBytes, err := base64.StdEncoding.DecodeString(resp.String())
if err != nil {
return "", fmt.Errorf("failed to decode user-data: %w", err)
}
rawBytes, err := ungzipIfNeeded(decodedBytes)
if err != nil {
return "", fmt.Errorf("failed to ungzip user-data: %w", err)
}
return string(rawBytes), nil
}
// hasGzipMagicNumber checks for the gzipMagic bytes at the beginning of the source
func hasGzipMagicNumber(source []byte) bool {
return bytes.HasPrefix(source, gzipMagic)
}
// ungzipIfNeeded checks for the gzip magic number and unzips the bytes if necessary,
// otherwise it returns the original raw bytes
func ungzipIfNeeded(raw []byte) ([]byte, error) {
if !hasGzipMagicNumber(raw) {
return raw, nil
}
reader, err := gzip.NewReader(bytes.NewReader(raw))
if err != nil {
return nil, err
}
defer reader.Close()
return io.ReadAll(reader)
}