Skip to content

jcbhmr/go-tempy

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

13 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

tempy for Go

๐Ÿ“‚ The tempy npm package ported to Go

fmt.Println(tempy.TemporaryFile(&tempy.FileOptions{Extension: "png"}))
// Possible output: /tmp/a1b2c3d4a1b2c3d4a1b2c3d4a1b2c3d4.png
p, err = tempy.TemporaryDirectory(&tempy.DirectoryOptions{Prefix: "name_"})
if err != nil {
  log.Fatal(err)
}
log.Println(p)
// Possible output: /tmp/name_a1b2c3d4a1b2c3d4a1b2c3d4a1b2c3d4

Docs | GitHub

๐Ÿ”— Properly resolves TMPDIR=/dirsymlink symlinks
๐Ÿฟ๏ธ Uses Go idioms while maintaining the same API surface as tempy
๐Ÿ“ Great for quickly writing some data to a temporary file

Installation

Go

go get github.com/jcbhmr/go-tempy/v3

Usage

Go

package main

import (
  "fmt"

  "github.com/jcbhmr/go-tempy/v3"
)

func main() {
  log.Println(tempy.TemporaryFile(nil))

  log.Println(tempy.TemporaryFile(&tempy.FileOptions{Extension: "png"}))

  log.Println(tempy.TemporaryFile(&tempy.FileOptions{Name: "unicorn.png"}))

  p, err = tempy.TemporaryDirectory(nil)
  if err != nil {
    log.Fatal(err)
  }
  log.Println(p)

  p, err = tempy.TemporaryDirectory(&tempy.DirectoryOptions{Prefix: "name_"})
  if err != nil {
    log.Fatal(err)
  }
  log.Println(p)

  // Possible output:
  // /tmp/a1b2c3d4a1b2c3d4a1b2c3d4a1b2c3d4
  // /tmp/a1b2c3d4a1b2c3d4a1b2c3d4a1b2c3d4.png
  // /tmp/unicorn.png
  // /tmp/a1b2c3d4a1b2c3d4a1b2c3d4a1b2c3d4
  // /tmp/name_a1b2c3d4a1b2c3d4a1b2c3d4a1b2c3d4
}

๐Ÿ“š See pkg.go.dev/github.com/jcbhmr/go-tempy/v3 for more docs

Development

Go

This package attempts to mirror the functionality and API surface of the tempy npm package. To that end, we need to convert some JavaScript concepts to Go concepts.

  • Union types like TypedArray | Buffer are mapped to any with a switch x.(type) or if v, ok := x.(T); ok. Doc comments should be included to clarify possible types.
  • If possible, JavaScript standard library or Node.js standard library types are mapped to Go standard library types.
  • Node.js Buffer is []byte. bytes.Buffer might seem like a good fit but it implements Reader and Writer interfaces which we don't want.
  • ArrayBuffer is []byte. bytes.Buffer offers too much functionality.
  • ECMA TypedArray variants are []<numeric>. Note that byte is an alias of uint8.
  • ECMA DataView is []byte. Byte slices can be views into other byte slices so this works OK.
  • Node.js R/W streams are io.(Read|Write)Closer interfaces. Node.js streams are closed by the stream's consumer. We do the same here.
  • All Promise<T> values are flattened to just T. We let the user spawn goroutines if they want things to be asynchronous.

Also try to keep the version tags in sync. v1.0.0 of tempy on npm should correspond with v1.0.0 of this module.