Linter and Drone config fixes, code linting.

This commit is contained in:
2021-11-20 23:06:40 +05:00
parent 9c045e9fd3
commit d5fcc5cef9
22 changed files with 152 additions and 146 deletions

View File

@@ -1,26 +1,21 @@
package httpserver
import (
// stdlib
"net"
"net/http"
"strings"
// local
"github.com/labstack/echo"
"go.dev.pztrn.name/giredore/internal/configuration"
"go.dev.pztrn.name/giredore/internal/structs"
// other
"github.com/labstack/echo"
)
func checkAllowedIPs() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(ec echo.Context) error {
return func(ectx echo.Context) error {
// Do nothing if request came not in "/_api" namespace.
if !strings.HasPrefix(ec.Request().RequestURI, "/_api") {
_ = next(ec)
return nil
if !strings.HasPrefix(ectx.Request().RequestURI, "/_api") {
return next(ectx)
}
// Get IPs and subnets from configuration and parse them
@@ -39,7 +34,9 @@ func checkAllowedIPs() echo.MiddlewareFunc {
_, net, err := net.ParseCIDR(ipToParse)
if err != nil {
log.Error().Err(err).Str("subnet", ipToParse).Msg("Failed to parse CIDR. /_api/ endpoint won't be accessible, this should be fixed manually in configuration file!")
return ec.JSON(http.StatusInternalServerError, &structs.Reply{Status: structs.StatusFailure, Errors: []structs.Error{structs.ErrInvalidAllowedIPDefined}})
// nolint:exhaustivestruct,wrapcheck
return ectx.JSON(http.StatusInternalServerError, &structs.Reply{Status: structs.StatusFailure, Errors: []structs.Error{structs.ErrInvalidAllowedIPDefined}})
}
subnets = append(subnets, net)
@@ -47,23 +44,24 @@ func checkAllowedIPs() echo.MiddlewareFunc {
// Check if requester's IP address are within allowed IP
// subnets.
ipToCheck := net.ParseIP(ec.RealIP())
ipToCheck := net.ParseIP(ectx.RealIP())
var allowed bool
for _, subnet := range subnets {
if subnet.Contains(ipToCheck) {
allowed = true
break
}
}
if allowed {
_ = next(ec)
return nil
return next(ectx)
}
return ec.JSON(http.StatusBadRequest, &structs.Reply{Status: structs.StatusFailure, Errors: []structs.Error{structs.ErrIPAddressNotAllowed}})
// nolint:exhaustivestruct,wrapcheck
return ectx.JSON(http.StatusBadRequest, &structs.Reply{Status: structs.StatusFailure, Errors: []structs.Error{structs.ErrIPAddressNotAllowed}})
}
}
}

View File

@@ -1,21 +1,17 @@
package httpserver
import (
// stdlib
"context"
"io/ioutil"
"net/http"
"strings"
"time"
// local
"go.dev.pztrn.name/giredore/internal/configuration"
"go.dev.pztrn.name/giredore/internal/logger"
// other
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"github.com/rs/zerolog"
"go.dev.pztrn.name/giredore/internal/configuration"
"go.dev.pztrn.name/giredore/internal/logger"
)
var (
@@ -66,6 +62,7 @@ func Start() {
}()
// Check that HTTP server was started.
// nolint:exhaustivestruct
httpc := &http.Client{Timeout: time.Second * 1}
checks := 0
@@ -78,9 +75,17 @@ func Start() {
time.Sleep(time.Second * 1)
resp, err := httpc.Get("http://" + configuration.Cfg.HTTP.Listen + "/_internal/waitForOnline")
localCtx, cancelFunc := context.WithTimeout(context.Background(), time.Second*1)
req, err := http.NewRequestWithContext(localCtx, "GET", "http://"+configuration.Cfg.HTTP.Listen+"/_internal/waitForOnline", nil)
if err != nil {
log.Panic().Err(err).Msg("Failed to create HTTP request!")
}
resp, err := httpc.Do(req)
if err != nil {
log.Debug().Err(err).Msg("HTTP error occurred, HTTP server isn't ready, waiting...")
continue
}
@@ -89,6 +94,7 @@ func Start() {
if err != nil {
log.Debug().Err(err).Msg("Failed to read response body, HTTP server isn't ready, waiting...")
continue
}
@@ -97,23 +103,29 @@ func Start() {
if resp.StatusCode == http.StatusOK {
if len(response) == 0 {
log.Debug().Msg("Response is empty, HTTP server isn't ready, waiting...")
continue
}
log.Debug().Int("status code", resp.StatusCode).Msgf("Response: %+v", string(response))
if len(response) == 17 {
// This is useless context cancel function call. Thanks to lostcancel linter.
cancelFunc()
break
}
}
}
log.Info().Msg("HTTP server is ready to process requests")
}
func waitForHTTPServerToBeUpHandler(ec echo.Context) error {
func waitForHTTPServerToBeUpHandler(ectx echo.Context) error {
response := map[string]string{
"error": "None",
}
return ec.JSON(200, response)
// nolint:wrapcheck
return ectx.JSON(200, response)
}

View File

@@ -1,8 +1,6 @@
package httpserver
import (
// other
"time"
"github.com/labstack/echo"
@@ -10,18 +8,18 @@ import (
func requestLogger() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(ec echo.Context) error {
return func(ectx echo.Context) error {
startTime := time.Now()
err := next(ec)
err := next(ectx)
log.Info().
Str("From", ec.RealIP()).
Str("To", ec.Request().Host).
Str("Method", ec.Request().Method).
Str("Path", ec.Request().URL.Path).
Int64("Length", ec.Request().ContentLength).
Str("UA", ec.Request().UserAgent()).
Str("From", ectx.RealIP()).
Str("To", ectx.Request().Host).
Str("Method", ectx.Request().Method).
Str("Path", ectx.Request().URL.Path).
Int64("Length", ectx.Request().ContentLength).
Str("UA", ectx.Request().UserAgent()).
TimeDiff("TimeMS", time.Now(), startTime).
Msg("HTTP request")

View File

@@ -1,12 +1,10 @@
package httpserver
import (
// stdlib
"encoding/json"
"fmt"
"net/http"
// other
"github.com/labstack/echo"
)
@@ -15,7 +13,7 @@ import (
type StrictJSONBinder struct{}
// Bind parses JSON input.
func (sjb *StrictJSONBinder) Bind(i interface{}, c echo.Context) error {
func (sjb *StrictJSONBinder) Bind(data interface{}, c echo.Context) error {
req := c.Request()
if req.ContentLength == 0 {
return echo.NewHTTPError(http.StatusBadRequest, "Request body can't be empty")
@@ -25,7 +23,9 @@ func (sjb *StrictJSONBinder) Bind(i interface{}, c echo.Context) error {
decoder := json.NewDecoder(req.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(i); err != nil {
// ToDo: rework this code.
// nolint:errorlint
if err := decoder.Decode(data); err != nil {
if ute, ok := err.(*json.UnmarshalTypeError); ok {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Unmarshal type error: expected=%v, got=%v, field=%v, offset=%v", ute.Type, ute.Value, ute.Field, ute.Offset))
} else if se, ok := err.(*json.SyntaxError); ok {