package comfuncimport ()// ParseEnvLineOption parse env line optionstypeParseEnvLineOptionstruct {// NotInlineComments dont parse inline comments. // - default: false. will parse inline comments NotInlineComments bool// SkipOnErrorLine skip error line, continue parse next line // - False: return error, clear parsed map SkipOnErrorLine bool}// ParseEnvLines parse simple multiline k-v string to a string-map.// Can use to parse simple INI or DOTENV file contents.//// NOTE://// - It's like INI/ENV format contents.// - Support comments line starts with: "#", ";", "//"// - Support inline comments split with: " #" eg: "name=tom # a comments"// - DON'T support submap parse.func ( string, ParseEnvLineOption) ( map[string]string, error) { := strings.Split(, "\n") := len()if == 0 {return } := make(map[string]string, )for , := range {if = strings.TrimSpace(); == "" {continue }// skip comments lineif [0] == '#' || [0] == ';' || strings.HasPrefix(, "//") {continue } , := splitLineByChar(, '=', !.NotInlineComments)// invalid lineif == "" {if .SkipOnErrorLine {continue } = nil = fmt.Errorf("invalid line contents: must match `KEY=VAL`(line: %s)", )return } [] = }return , nil}// SplitLineToKv parse string line to k-v, not support comments.//// Example://// 'DEBUG=true' => ['DEBUG', 'true']//// NOTE: line must contain '=', allow: 'ENV_KEY='func (, string) (string, string) {returnSplitKvBySep(, , false)}// SplitKvBySep parse string line to k-v, support parse comments.// - rmInlineComments: check and remove inline comments by ' #'func (, string, bool) (, string) { := strings.Index(, )if < 0 {return }returnsplitKvBySepPos(, , len(), )}func splitLineByChar( string, byte, bool) (, string) { := strings.IndexByte(, )if < 0 {return }returnsplitKvBySepPos(, , 1, )}func splitKvBySepPos( string, , int, bool) (, string) {// key cannot be empty = strings.TrimSpace([0:])if == "" {return"", "" } = strings.TrimSpace([+:])// check quotes if presentif := len(); >= 2 {// remove quotesif ([0] == '"' && [-1] == '"') || ([0] == '\'' && [-1] == '\'') { = [1 : -1]return }if ! {return }// value is empty, only inline commentsif [0] == '#' { = ""return }// remove inline commentsif := strings.Index(, " #"); > 0 { = strings.TrimRight([0:], " \t") = len()// remove quotesif ([0] == '"' && [-1] == '"') || ([0] == '\'' && [-1] == '\'') { = [1 : -1]return } } }return}
The pages are generated with Goldsv0.8.4. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.