2020-12-11 02:11:49 +03:00
|
|
|
package file
|
|
|
|
|
|
|
|
import (
|
2024-04-17 14:57:30 +03:00
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
"regexp"
|
|
|
|
|
2023-08-14 23:50:12 +03:00
|
|
|
"go.unistack.org/micro/v4/options"
|
2024-04-17 14:57:30 +03:00
|
|
|
"golang.org/x/text/transform"
|
2020-12-11 02:11:49 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
type pathKey struct{}
|
|
|
|
|
2023-08-14 23:50:12 +03:00
|
|
|
func Path(path string) options.Option {
|
|
|
|
return options.ContextOption(pathKey{}, path)
|
2021-11-18 16:12:12 +03:00
|
|
|
}
|
2024-04-17 14:57:30 +03:00
|
|
|
|
|
|
|
type readerKey struct{}
|
|
|
|
|
|
|
|
func Reader(r io.Reader) options.Option {
|
|
|
|
return options.ContextOption(readerKey{}, r)
|
|
|
|
}
|
|
|
|
|
|
|
|
type transformerKey struct{}
|
|
|
|
|
|
|
|
type TransformerFunc func(src []byte, index []int) []byte
|
|
|
|
|
|
|
|
func Transformer(t transform.Transformer) options.Option {
|
|
|
|
return options.ContextOption(transformerKey{}, t)
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewEnvTransformer(rs string, trimLeft, trimRight int) (*EnvTransformer, error) {
|
|
|
|
re, err := regexp.Compile(rs)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &EnvTransformer{
|
|
|
|
Regexp: re,
|
|
|
|
TransformerFunc: func(src []byte, index []int) []byte {
|
|
|
|
var envKey string
|
|
|
|
if len(src) > index[1]-trimRight {
|
|
|
|
envKey = string(src[index[0]+trimLeft : index[1]-trimRight])
|
|
|
|
}
|
|
|
|
|
|
|
|
if envVal, ok := os.LookupEnv(envKey); ok {
|
|
|
|
return []byte(envVal)
|
|
|
|
}
|
|
|
|
|
|
|
|
return src[index[0]:index[1]]
|
|
|
|
},
|
|
|
|
}, nil
|
|
|
|
}
|