Skip to content

Commit

Permalink
extract method PositiveIntParamStrict()
Browse files Browse the repository at this point in the history
  • Loading branch information
mikebd committed Oct 9, 2023
1 parent 9ab2887 commit 989f151
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 20 deletions.
23 changes: 23 additions & 0 deletions controller/rest/util/param.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package util

import (
"fmt"
"net/http"
"strconv"
)

// PositiveIntParamStrict returns the value of the parameter as an int (>= 0), or the default value if the parameter is not present
func PositiveIntParamStrict(w http.ResponseWriter, r *http.Request, defaultValue int, param string) (int, error) {
paramValue := r.URL.Query().Get(param)
if paramValue == "" {
return defaultValue, nil
}

intParam, err := strconv.Atoi(paramValue)
if intParam < 0 || err != nil {
RenderTextPlain(w, nil, fmt.Errorf("invalid value for parameter '%s': '%s'", param, paramValue))
return 0, err
}

return intParam, nil
}
31 changes: 11 additions & 20 deletions controller/rest/v1/logs.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
package v1

import (
"fmt"
"github.com/julienschmidt/httprouter"
"go-read-var-log/config"
"go-read-var-log/controller/rest/util"
"go-read-var-log/service"
"log"
"net/http"
"slices"
"strconv"
"time"
)

Expand All @@ -29,24 +27,17 @@ func GetLog(w http.ResponseWriter, r *http.Request, p httprouter.Params) {

logFilename := p.ByName("log")

maxLines := config.GetArguments().NumberOfLogLines
maxLinesParam := r.URL.Query().Get("n")
if maxLinesParam != "" {
intParam, err := strconv.Atoi(maxLinesParam)
if err == nil && intParam > 0 {
maxLines = intParam
} else {
util.RenderTextPlain(w, nil, fmt.Errorf("invalid value for parameter 'n': '%s'", maxLinesParam))
return
}
}

logEvents, err := service.GetLog(config.LogDirectory, logFilename, maxLines)
maxLines, _ := util.PositiveIntParamStrict(w, r, config.GetArguments().NumberOfLogLines, "n")
if maxLines > 0 {
logEvents, err := service.GetLog(config.LogDirectory, logFilename, maxLines)

// Reverse the slice - we want the most recent events first.
// Tests to see if this is slower than just iterating backwards when rendering
// showed that it was not. This is easier to read for maintainability.
slices.Reverse(logEvents)
if err == nil {
// Reverse the slice - we want the most recent events first.
// Tests to see if this is slower than just iterating backwards when rendering
// showed that it was not. This is easier to read for maintainability.
slices.Reverse(logEvents)
}

util.RenderTextPlain(w, logEvents, err)
util.RenderTextPlain(w, logEvents, err)
}
}

0 comments on commit 989f151

Please sign in to comment.