Skip to content

Commit

Permalink
Moving utility functions shared between httpproxy and smtp to dedicat…
Browse files Browse the repository at this point in the history
…ed package
  • Loading branch information
Lucas Hinderberger committed Jun 24, 2024
1 parent 878c291 commit e3b244f
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 49 deletions.
39 changes: 39 additions & 0 deletions internal/handlerutil/util.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package handlerutil

import (
"encoding/json"
"net/http"

"github.com/sirupsen/logrus"
)

// errorResponse definition
type errorResponse struct {
Error string `json:"error"`
}

// LogH is a middleware that logs requests via logrus.Debugf.
func LogH(skipLogs bool, next http.Handler) http.Handler {
if skipLogs {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logrus.Debugf("http-server: %s: %q", r.Method, r.URL)
next.ServeHTTP(w, r)
})
}

// RespondWithErr responds using a JSON-serialized error message.
func RespondWithErr(w http.ResponseWriter, status int, err error) {
RespondWithJSON(w, status, errorResponse{err.Error()})
}

// RespondWithJSON responds with a JSON-serialized value.
func RespondWithJSON(w http.ResponseWriter, status int, v any) {
w.WriteHeader(status)

err := json.NewEncoder(w).Encode(v)
if err != nil {
logrus.Errorf("Could not encode JSON response: %s (%v)", err, v)
}
}
17 changes: 3 additions & 14 deletions internal/httpproxy/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package httpproxy
import (
"net/http"

"github.com/sirupsen/logrus"
"github.com/programmfabrik/apitest/internal/handlerutil"
)

// ProxyConfig definition
Expand All @@ -24,18 +24,7 @@ func New(cfg ProxyConfig) *Proxy {
// RegisterRoutes for the proxy store/retrieve
func (proxy *Proxy) RegisterRoutes(mux *http.ServeMux, prefix string, skipLogs bool) {
for _, s := range *proxy {
mux.Handle(prefix+"proxywrite/"+s.Name, LogH(skipLogs, http.HandlerFunc(s.write)))
mux.Handle(prefix+"proxyread/"+s.Name, LogH(skipLogs, http.HandlerFunc(s.read)))
mux.Handle(prefix+"proxywrite/"+s.Name, handlerutil.LogH(skipLogs, http.HandlerFunc(s.write)))
mux.Handle(prefix+"proxyread/"+s.Name, handlerutil.LogH(skipLogs, http.HandlerFunc(s.read)))
}
}

// TODO: Move to utility package?
func LogH(skipLogs bool, next http.Handler) http.Handler {
if skipLogs {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logrus.Debugf("http-server: %s: %q", r.Method, r.URL)
next.ServeHTTP(w, r)
})
}
33 changes: 7 additions & 26 deletions internal/httpproxy/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import (
"strconv"

"github.com/pkg/errors"
"github.com/sirupsen/logrus"

"github.com/programmfabrik/apitest/internal/handlerutil"
)

// Mode definition
Expand All @@ -20,11 +21,6 @@ const (
ModePassthrough Mode = "passthru"
)

// errorResponse definition
type errorResponse struct {
Error string `json:"error"`
}

// request definition
type request struct {
Method string `json:"method"`
Expand Down Expand Up @@ -69,7 +65,7 @@ func (st *store) write(w http.ResponseWriter, r *http.Request) {
if r.Body != nil {
reqData.Body, err = ioutil.ReadAll(r.Body)
if err != nil {
RespondWithErr(w, http.StatusInternalServerError, errors.Errorf("Could not read request body: %s", err))
handlerutil.RespondWithErr(w, http.StatusInternalServerError, errors.Errorf("Could not read request body: %s", err))
return
}
}
Expand All @@ -80,7 +76,7 @@ func (st *store) write(w http.ResponseWriter, r *http.Request) {
Offset int `json:"offset"`
}{offset})
if err != nil {
RespondWithErr(w, http.StatusInternalServerError, errors.Errorf("Could not encode response: %s", err))
handlerutil.RespondWithErr(w, http.StatusInternalServerError, errors.Errorf("Could not encode response: %s", err))
}
}

Expand All @@ -98,14 +94,14 @@ func (st *store) read(w http.ResponseWriter, r *http.Request) {
if offsetStr != "" {
offset, err = strconv.Atoi(offsetStr)
if err != nil {
RespondWithErr(w, http.StatusBadRequest, errors.Errorf("Invalid offset %s", offsetStr))
handlerutil.RespondWithErr(w, http.StatusBadRequest, errors.Errorf("Invalid offset %s", offsetStr))
return
}
}

count := len(st.Data)
if offset >= count {
RespondWithErr(w, http.StatusBadRequest, errors.Errorf("Offset (%d) is higher than count (%d)", offset, count))
handlerutil.RespondWithErr(w, http.StatusBadRequest, errors.Errorf("Offset (%d) is higher than count (%d)", offset, count))
return
}

Expand All @@ -130,21 +126,6 @@ func (st *store) read(w http.ResponseWriter, r *http.Request) {

_, err = w.Write(req.Body)
if err != nil {
RespondWithErr(w, http.StatusInternalServerError, errors.Errorf("Could not encode response: %s", err))
}
}

// TODO: Move to utility package?
func RespondWithErr(w http.ResponseWriter, status int, err error) {
RespondWithJSON(w, status, errorResponse{err.Error()})
}

// TODO: Move to utility package?
func RespondWithJSON(w http.ResponseWriter, status int, v any) {
w.WriteHeader(status)

err := json.NewEncoder(w).Encode(v)
if err != nil {
logrus.Errorf("Could not encode JSON response: %s (%v)", err, v)
handlerutil.RespondWithErr(w, http.StatusInternalServerError, errors.Errorf("Could not encode response: %s", err))
}
}
18 changes: 9 additions & 9 deletions internal/smtp/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"strconv"
"strings"

"github.com/programmfabrik/apitest/internal/httpproxy"
"github.com/programmfabrik/apitest/internal/handlerutil"
)

type smtpHTTPHandler struct {
Expand All @@ -23,8 +23,8 @@ func (s *Server) RegisterRoutes(mux *http.ServeMux, prefix string, skipLogs bool
prefix: path.Join(prefix, "smtp"),
}

mux.Handle(handler.prefix, httpproxy.LogH(skipLogs, handler))
mux.Handle(handler.prefix+"/", httpproxy.LogH(skipLogs, handler))
mux.Handle(handler.prefix, handlerutil.LogH(skipLogs, handler))
mux.Handle(handler.prefix+"/", handlerutil.LogH(skipLogs, handler))
}

func (h *smtpHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
Expand All @@ -44,7 +44,7 @@ func (h *smtpHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// was already handled above.
idx, err := strconv.Atoi(pathParts[0])
if err != nil {
httpproxy.RespondWithErr(
handlerutil.RespondWithErr(
w, http.StatusBadRequest,
fmt.Errorf("could not parse message index: %w", err),
)
Expand All @@ -68,7 +68,7 @@ func (h *smtpHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if pathParts[1] == "multipart" {
partIdx, err := strconv.Atoi(pathParts[2])
if err != nil {
httpproxy.RespondWithErr(
handlerutil.RespondWithErr(
w, http.StatusBadRequest,
fmt.Errorf("could not parse multipart index: %w", err),
)
Expand Down Expand Up @@ -107,7 +107,7 @@ func (h *smtpHTTPHandler) handleMessageIndex(w http.ResponseWriter, r *http.Requ
out["count"] = len(receivedMessages)
out["messages"] = messagesOut

httpproxy.RespondWithJSON(w, http.StatusOK, out)
handlerutil.RespondWithJSON(w, http.StatusOK, out)
}

func (h *smtpHTTPHandler) handleMessageMeta(w http.ResponseWriter, r *http.Request, idx int) {
Expand Down Expand Up @@ -142,7 +142,7 @@ func (h *smtpHTTPHandler) handleMultipartIndex(w http.ResponseWriter, r *http.Re
out["count"] = len(multiparts)
out["multiparts"] = multipartsOut

httpproxy.RespondWithJSON(w, http.StatusOK, out)
handlerutil.RespondWithJSON(w, http.StatusOK, out)
}

func (h *smtpHTTPHandler) handleMultipartMeta(
Expand Down Expand Up @@ -181,7 +181,7 @@ func (h *smtpHTTPHandler) handleMultipartBody(
func (h *smtpHTTPHandler) retrieveMessage(w http.ResponseWriter, idx int) *ReceivedMessage {
msg, err := h.server.ReceivedMessage(idx)
if err != nil {
httpproxy.RespondWithErr(w, http.StatusNotFound, err)
handlerutil.RespondWithErr(w, http.StatusNotFound, err)
return nil
}

Expand All @@ -208,7 +208,7 @@ func ensureIsMultipart(w http.ResponseWriter, msg *ReceivedMessage) bool {
return true
}

httpproxy.RespondWithErr(w, http.StatusNotFound, fmt.Errorf(
handlerutil.RespondWithErr(w, http.StatusNotFound, fmt.Errorf(
"multipart information was requested for non-multipart message",
))

Expand Down

0 comments on commit e3b244f

Please sign in to comment.