libnetwork: inline sendKey() into SetExternalKey()

This function included a defer to close the net.Conn if an error occurred,
but the calling function (SetExternalKey()) also had a defer to close it
unconditionally.

Rewrite it to use json.NewEncoder(), which accepts a writer, and inline
the code.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
Sebastiaan van Stijn 2023-04-28 12:38:08 +02:00
parent 9d8fcb3296
commit 1e9ebfb00c
No known key found for this signature in database
GPG key ID: 76698F39D527CE8C

View file

@ -70,11 +70,6 @@ func setKey() error {
// SetExternalKey provides a convenient way to set an External key to a sandbox
func SetExternalKey(shortCtlrID string, containerID string, key string, execRoot string) error {
keyData := setKeyData{
ContainerID: containerID,
Key: key,
}
uds := filepath.Join(execRoot, execSubdir, shortCtlrID+".sock")
c, err := net.Dial("unix", uds)
if err != nil {
@ -82,29 +77,16 @@ func SetExternalKey(shortCtlrID string, containerID string, key string, execRoot
}
defer c.Close()
if err = sendKey(c, keyData); err != nil {
err = json.NewEncoder(c).Encode(setKeyData{
ContainerID: containerID,
Key: key,
})
if err != nil {
return fmt.Errorf("sendKey failed with : %v", err)
}
return processReturn(c)
}
func sendKey(c net.Conn, data setKeyData) error {
var err error
defer func() {
if err != nil {
c.Close()
}
}()
var b []byte
if b, err = json.Marshal(data); err != nil {
return err
}
_, err = c.Write(b)
return err
}
func processReturn(r io.Reader) error {
buf := make([]byte, 1024)
n, err := r.Read(buf[:])