-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfmt_flag.go
75 lines (64 loc) · 1.88 KB
/
fmt_flag.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright (c) Jeevanandam M. (https://github.com/jeevatkm)
// go-aah/essentials source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package ess
import (
"fmt"
"strings"
)
var (
// FmtFlagSeparator is used parse flags pattern.
FmtFlagSeparator = "%"
// FmtFlagValueSeparator is used to parse into flag and value.
FmtFlagValueSeparator = ":"
defaultFormat = "%v"
)
type (
// FmtFlagPart is indiviual flag details
// For e.g.:
// part := FmtFlagPart{
// Flag: FmtFlagTime,
// Name: "time",
// Format: "2006-01-02 15:04:05.000",
// }
FmtFlagPart struct {
Flag FmtFlag
Name string
Format string
}
// FmtFlag type definition
FmtFlag uint8
)
// ParseFmtFlag it parses the given pattern, format flags into format flag parts.
// For e.g.:
// %time:2006-01-02 15:04:05.000 %level:-5 %message
// %clientip %reqid %reqtime %restime %resstatus %ressize %reqmethod %requrl %reqhdr:Referer %reshdr:Server
func ParseFmtFlag(pattern string, fmtFlags map[string]FmtFlag) ([]FmtFlagPart, error) {
var flagParts []FmtFlagPart
pattern = strings.TrimSpace(pattern)
formatFlags := strings.Split(pattern, FmtFlagSeparator)[1:]
for _, f := range formatFlags {
f = strings.TrimSpace(f)
parts := strings.SplitN(f, FmtFlagValueSeparator, 2)
flag, found := fmtFlags[parts[0]]
if !found {
return nil, fmt.Errorf("fmtflag: unknown flag '%s'", f)
}
part := FmtFlagPart{Flag: flag, Name: parts[0]}
switch len(parts) {
case 2:
// handle `time` related flag, `custom` flag
// and `hdr` flag particularly
if strings.Contains(parts[0], "time") || parts[0] == "custom" ||
strings.HasSuffix(parts[0], "hdr") {
part.Format = parts[1]
} else {
part.Format = "%" + parts[1] + "v"
}
default:
part.Format = defaultFormat
}
flagParts = append(flagParts, part)
}
return flagParts, nil
}