Conditions | 15 |
Total Lines | 58 |
Code Lines | 34 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
Complex classes like rest.Logger often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
1 | package rest |
||
93 | func Logger(flags ...LoggerFlag) func(http.Handler) http.Handler { |
||
94 | |||
95 | inFlags := func(f LoggerFlag) bool { |
||
96 | for _, flg := range flags { |
||
97 | if flg == LogAll || flg == f { |
||
98 | return true |
||
99 | } |
||
100 | } |
||
101 | return false |
||
102 | } |
||
103 | |||
104 | f := func(h http.Handler) http.Handler { |
||
105 | |||
106 | fn := func(w http.ResponseWriter, r *http.Request) { |
||
107 | ww := middleware.NewWrapResponseWriter(w, 1) |
||
108 | |||
109 | body := func() (result string) { |
||
110 | if inFlags(LogBody) { |
||
111 | if content, err := ioutil.ReadAll(r.Body); err == nil { |
||
112 | result = string(content) |
||
113 | r.Body = ioutil.NopCloser(bytes.NewReader(content)) |
||
114 | |||
115 | if len(result) > 0 { |
||
116 | result = strings.ReplaceAll(result, "\n", " ") |
||
117 | result = reMultWhtsp.ReplaceAllString(result, " ") |
||
118 | } |
||
119 | |||
120 | if len(result) > maxBody { |
||
121 | result = result[:maxBody] + "..." |
||
122 | } |
||
123 | } |
||
124 | } |
||
125 | return result |
||
126 | }() |
||
127 | |||
128 | t1 := time.Now() |
||
129 | defer func() { |
||
130 | t2 := time.Now() |
||
131 | |||
132 | q := r.URL.String() |
||
133 | if qun, err := url.QueryUnescape(q); err == nil { |
||
134 | q = qun |
||
135 | } |
||
136 | // hide id and pin |
||
137 | regex := regexp.MustCompile(`favicon\.ico$`) |
||
138 | if !regex.MatchString(q) { |
||
139 | log.Printf("[DEBUG] REST %s - %s - %s - %d (%d) - %v %s", |
||
140 | r.Method, q, strings.Split(r.RemoteAddr, ":")[0], |
||
141 | ww.Status(), ww.BytesWritten(), t2.Sub(t1), body) |
||
142 | } |
||
143 | }() |
||
144 | |||
145 | h.ServeHTTP(ww, r) |
||
146 | } |
||
147 | return http.HandlerFunc(fn) |
||
148 | } |
||
149 | |||
150 | return f |
||
151 | } |
||
152 |