From a1d98823f8d17b49b432508d071b62ccd426f1ce Mon Sep 17 00:00:00 2001 From: Ophestra Date: Wed, 2 Jul 2025 21:23:55 +0900 Subject: hakurei: move container toplevel Signed-off-by: Ophestra --- params.go | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 params.go (limited to 'params.go') diff --git a/params.go b/params.go new file mode 100644 index 00000000..47441235 --- /dev/null +++ b/params.go @@ -0,0 +1,47 @@ +package hakurei + +import ( + "encoding/gob" + "errors" + "os" + "strconv" +) + +var ( + ErrNotSet = errors.New("environment variable not set") + ErrInvalid = errors.New("bad file descriptor") +) + +// Setup appends the read end of a pipe for setup params transmission and returns its fd. +func Setup(extraFiles *[]*os.File) (int, *gob.Encoder, error) { + if r, w, err := os.Pipe(); err != nil { + return -1, nil, err + } else { + fd := 3 + len(*extraFiles) + *extraFiles = append(*extraFiles, r) + return fd, gob.NewEncoder(w), nil + } +} + +// Receive retrieves setup fd from the environment and receives params. +func Receive(key string, e any, v **os.File) (func() error, error) { + var setup *os.File + + if s, ok := os.LookupEnv(key); !ok { + return nil, ErrNotSet + } else { + if fd, err := strconv.Atoi(s); err != nil { + return nil, err + } else { + setup = os.NewFile(uintptr(fd), "setup") + if setup == nil { + return nil, ErrInvalid + } + if v != nil { + *v = setup + } + } + } + + return setup.Close, gob.NewDecoder(setup).Decode(e) +} -- cgit v1.3.1