nix-amer/internal/cnf/nginx.go

103 lines
2.0 KiB
Go
Raw Normal View History

package cnf
import (
lib "git.xdrm.io/go/nix-amer/internal/cnf/parser/nginx"
"io"
"strings"
)
type nginx struct {
data *lib.Model
parsed bool
}
// ReadFrom implements io.ReaderFrom
func (d *nginx) ReadFrom(_reader io.Reader) (int64, error) {
d.data = new(lib.Model)
// 1. get nginx decoder
decoder := lib.NewDecoder(_reader)
err := decoder.Decode(d.data)
if err != nil {
return 0, err
}
d.parsed = true
return 0, nil
}
// WriteTo implements io.WriterTo
func (d *nginx) WriteTo(_writer io.Writer) (int64, error) {
encoder := lib.NewEncoder(_writer)
return 0, encoder.Encode(d.data)
}
// browse returns the target of a dot-separated path (as an interface{} chain where the last is the target if found)
func (d *nginx) browse(_path string) ([][]*lib.Line, bool) {
// 1. extract path
path := strings.Split(_path, ".")
if len(path) > 0 { // remove last field
path = path[:len(path)-1]
}
// 2. init output chain
var current []*lib.Line = d.data.Lines
chain := make([][]*lib.Line, 0, len(path)+1)
chain = append(chain, current)
// 3. iterate over path / nested fields
for _, field := range path {
for _, child := range current {
if child.Type == lib.SECTION && child.Components[0] == field {
current = child.Lines
chain = append(chain, current)
break
}
}
return chain, false
}
return chain, true
}
// Get returns the value of a dot-separated path, and if it exists
func (d *nginx) Get(_path string) (string, bool) {
// 1. browse path
chain, found := d.browse(_path)
if !found {
return "", false
}
// 2. Get last field
fields := strings.Split(_path, ".")
field := fields[len(fields)-1]
// 3. search in last chain element
last := chain[len(chain)-1]
for _, line := range last {
// 4. return value
if line.Type == lib.ASSIGNMENT && line.Components[0] == field {
return line.Components[1], true
}
}
return "", false
}
// Set the value of a dot-separated path, and creates it if not found
func (d *nginx) Set(_path, _value string) bool {
return false
}