# Use the Go library

Add the dmog module to a Go program, translate a string or a stream, run a program, read a failure, set a limit, and stop a run with its context.

The module `github.com/tabnas/dmog/go` is a library, package `dmog`, as well as the `dmog` command. A Go program that imports it can do everything the command does. The package does no input or output but through the reader and the writer a call is given: it opens no file, handles no signal, and never exits. The examples on this page are the package's own, which `go test` runs, and each prints what its `Output` comment shows. Every function and option is in [the library reference](https://dmog.tabnas.dev/reference/library.html).

## Add the module

You need Go 1.24 or later. Add the module to yours:

```sh
go get github.com/tabnas/dmog/go
```

Import its package as `dmog "github.com/tabnas/dmog/go"`, as the examples do.

## Translate a document held in a string

`NewTranslation` takes the translation's options and compiles it, and `RunString` runs it over a string. A translation compiles once and runs as often as you like:

```go
// A translation compiled once runs over many inputs.
func ExampleNewTranslation() {
	translation, err := dmog.NewTranslation(dmog.TranslateOptions{From: "csv", To: "json"})
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, input := range []string{"name,age\nAda,36\n", "name\nAlan\n"} {
		output, err := translation.RunString(context.Background(), input)
		if err != nil {
			fmt.Println(err)
		}
		fmt.Print(output)
	}
	// Output:
	// [{"name":"Ada","age":"36"}]
	// [{"name":"Alan"}]
}
```

The options are the command's. `From` and `To` name formats by the ids `dmog formats` prints, and `Path`, `Key`, `With`, and `Whole` stand for `--path`, `--key`, `--with`, and `--whole`. `NewTranslation` refuses a format that does not exist, a path that does not parse, and a program that does not check, before any input is read.

## Stream from a file

`Run` reads from an `io.Reader` and writes to an `io.Writer` as it reads:

```go
// A translation compiled once reads a file as it writes the output.
func ExampleTranslation_Run() {
	translation, err := dmog.NewTranslation(dmog.TranslateOptions{From: "yaml", To: "toml"})
	if err != nil {
		fmt.Println(err)
		return
	}
	input, err := os.Open("testdata/server.yaml")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer input.Close()
	if err := translation.Run(context.Background(), input, os.Stdout); err != nil {
		fmt.Println(err)
	}
	// Output:
	// "server" = { "host" = "example.com", "port" = 8080, "tls" = true }
	// "paths" = [ "/api", "/health" ]
}
```

`Translate` does the same in one call: it compiles the translation and runs it once.

A document that cannot be streamed, such as an object that repeats a key, fails with a message that ends by naming `--whole`. Set `Whole` to read it whole, as [Translate a document that cannot be streamed](https://dmog.tabnas.dev/how-to/read-whole.html) does with the command.

## Run a program

`NewProgram` takes an alchemy program as a `Source`, its name and its text, with the options of `dmog run`. `Run` and `RunString` run it over a JSON document:

```go
// A program binds a table to the columns its document describes, and the
// table is rendered as JSON records.
func ExampleProgram() {
	table := dmog.Source{Name: "table.alc", Text: `def column-from-meta [source]
  record
    entry :label (get "title" source)
    entry :source
      as-path
        get "path" source

def binding
  record
    entry :columns
      path "fields"
    entry :rows
      path "records" each-index
    entry :column column-from-meta

def export [input]
  table-from-json binding input
`}
	program, err := dmog.NewProgram(table, dmog.ProgramOptions{Render: dmog.RenderJSON})
	if err != nil {
		fmt.Println(err)
		return
	}
	input := `{"fields":[{"title":"Name","path":["name"]}],"records":[{"name":"Ada"},{"name":"Alan"}]}`
	output, err := program.RunString(context.Background(), input)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Print(output)
	// Output: [{"Name":"Ada"},{"Name":"Alan"}]
}
```

`Render` stands for `--render`, and `Grammar` for `--grammar`. `NewProgram` refuses a program that does not check, and a `Render` its export cannot take, before any input is read. `Canon`, `Format`, `Check`, `Explain`, and `ExplainJSON` answer what the commands of those names print. To reshape a document while it is translated, give the program to a translation as its `With` option.

## Read a failure

Every error the package returns is a `*dmog.Fail`, which `errors.As` reads. Its `Code` is the failure's stable name, and `CommittedOutput` says whether output had been written before it:

```go
// A failure is a *dmog.Fail: its code, where it was found, and whether
// output had been written before it.
func ExampleTranslate_failure() {
	input := strings.NewReader(`{"a":`)
	err := dmog.Translate(context.Background(), input, io.Discard, dmog.TranslateOptions{From: "json", To: "yaml"})
	var fail *dmog.Fail
	if !errors.As(err, &fail) {
		fmt.Println(err)
		return
	}
	if fail.Code == dmog.CodeInputInvalid {
		fmt.Println("not JSON, at line", fail.Row)
	}
	fmt.Println(fail.CommittedOutput)
	object, _ := json.Marshal(fail)
	fmt.Println(string(object))
	// Output:
	// not JSON, at line 1
	// false
	// {"code":"INPUT_INVALID","message":"unexpected: unexpected character(s):","row":1,"col":6,"output":"none"}
}
```

Output written before a failure is a prefix of the answer, and ends with a whole record unless one record was longer than the 32 KiB the writer holds back. `RunString` returns it along with the failure. `json.Marshal` writes a failure as the object the command writes on standard error, and [Failures](https://dmog.tabnas.dev/reference/failures.html) lists every code.

## Set a limit

A translation or a program whose `Limits` is `nil` runs under the command's limits. To change one, change it on a copy of `DefaultLimits`, since a zero `Limits` holds none of them. A run that would pass a limit fails with `CodeResourceLimitExceeded`, naming it:

```go
// A limit is set on a copy of DefaultLimits. A run that reaches it fails
// with CodeResourceLimitExceeded, naming it.
func ExampleTranslation_RunString_limit() {
	limits := dmog.DefaultLimits()
	most := uint64(16)
	limits.MaxOutputBytes = &most
	translation, err := dmog.NewTranslation(dmog.TranslateOptions{From: "csv", To: "json", Limits: &limits})
	if err != nil {
		fmt.Println(err)
		return
	}
	_, err = translation.RunString(context.Background(), "name\nAda\nAlan\n")
	var fail *dmog.Fail
	if errors.As(err, &fail) {
		fmt.Println(fail.Code, fail.Limit.Name, fail.CommittedOutput)
	}
	// Output: RESOURCE_LIMIT_EXCEEDED max_output_bytes false
}
```

`MaxOutputBytes` is `--max-output-bytes`, and `nil` there means no limit. A translation or a program copies its limits when it is compiled, so a later change to the copy reaches no run.

## Stop a run

A run stops when its context ends, and fails with `CodeAborted`. A context that has already ended fails the run before it reads anything:

```go
// endless is a JSON array that never ends: [0,0,0,...
type endless struct{ n int }

func (e *endless) Read(p []byte) (int, error) {
	for i := range p {
		switch {
		case e.n == 0:
			p[i] = '['
		case e.n%2 == 1:
			p[i] = '0'
		default:
			p[i] = ','
		}
		e.n++
	}
	return len(p), nil
}

// A run whose context ends stops, and fails with CodeAborted.
func ExampleTranslation_Run_cancel() {
	translation, err := dmog.NewTranslation(dmog.TranslateOptions{From: "json", To: "yaml"})
	if err != nil {
		fmt.Println(err)
		return
	}
	ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
	defer cancel()
	err = translation.Run(ctx, &endless{}, io.Discard)
	var fail *dmog.Fail
	if errors.As(err, &fail) {
		fmt.Println(fail.Code)
	}
	// Output: ABORTED
}
```

The run looks at its context before every read and between the steps of its work. A read that blocks, such as one from a network connection that stops sending, holds the run until the read returns, so give such a reader a deadline of its own, as `SetReadDeadline` does for a `net.Conn`.
