sniplib

package
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 17, 2023 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package sniplib converts Go code snippets to full programs and runs them.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Run

func Run(source string, stdin io.Reader, stdout, stderr io.Writer) error

Run runs the given Go program source. Use the provided stdin reader and stdout/stderr writers for I/O.

Example
package main

import (
	"fmt"
	"os"

	"github.com/benhoyt/gosnip/sniplib"
)

func main() {
	source := `
package main

import "fmt"

func main() {
	fmt.Println("Hello world")
}
`
	err := sniplib.Run(source, os.Stdin, os.Stdout, os.Stderr)
	if err != nil {
		fmt.Println(err)
		return
	}
}
Output:

Hello world

func ToProgram

func ToProgram(statements, imports []string) (string, error)

ToProgram converts a slice of Go statements to a full Go program. References to standard library functions and functions from packages in GOPATH are imported automatically (using the same logic as the "goimports" tool).

The "imports" arg is an explicit list of imports, only needed for selecting between ambiguous stdlib import names like "text/template" and "html/template". Returns the formatted source text of the full Go program and any error that occurred.

Example
package main

import (
	"fmt"

	"github.com/benhoyt/gosnip/sniplib"
)

func main() {
	statements := []string{`fmt.Println("Hello world")`}
	source, err := sniplib.ToProgram(statements, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Print(source)
}
Output:

package main

import "fmt"

func main() {
	fmt.Println("Hello world")
}
Example (Imports)
package main

import (
	"fmt"

	"github.com/benhoyt/gosnip/sniplib"
)

func main() {
	statements := []string{`fmt.Println(template.HTMLEscapeString("<b>"))`}
	imports := []string{"text/template"}
	source, err := sniplib.ToProgram(statements, imports)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Print(source)
}
Output:

package main

import (
	"fmt"
	"text/template"
)

func main() {
	fmt.Println(template.HTMLEscapeString("<b>"))
}

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL