Skip to content

Commit

Permalink
add enc/dec json
Browse files Browse the repository at this point in the history
  • Loading branch information
tomiok committed Jul 3, 2023
1 parent ab46492 commit 4e3dbd8
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
5 changes: 2 additions & 3 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,13 @@ func Unwrap(h WebHandler) http.HandlerFunc {

if err != nil {
requestID := middleware.GetReqID(r.Context())
evt := log.Error().Caller(2).Err(err)
evt := log.Error().Err(err)
if requestID != "" {
evt = evt.Str("RequestID", requestID)
}

evt.Msg("cannot process request")

wrapErrorResponse(w, err)
wrapErrorResponse(w, requestID, err)
}
}
}
33 changes: 29 additions & 4 deletions web.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@ package webh
import (
"encoding/json"
"errors"
"github.com/rs/zerolog/log"
"io"
"net/http"
)

type HttpResponse struct {
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
Success bool `json:"success"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
Success bool `json:"success"`
RequestID string `json:"request_id,omitempty"`
}

type ErrHTTP struct {
Expand All @@ -21,14 +24,16 @@ func (e ErrHTTP) Error() string {
return e.Message
}

func wrapErrorResponse(w http.ResponseWriter, err error) {
func wrapErrorResponse(w http.ResponseWriter, requestID string, err error) {
_err := transform(err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(_err.Code)

r, _ := json.Marshal(HttpResponse{
Message: _err.Message,
Success: false,

RequestID: requestID,
})
_, _ = w.Write(r)
}
Expand All @@ -45,3 +50,23 @@ func transform(e error) *ErrHTTP {
Code: http.StatusInternalServerError,
}
}

// EJson is the shorthand to encode JSON.
func EJson(w io.Writer, v any) error {
return json.NewEncoder(w).Encode(v)
}

// Djson is a generic way to unmarshal your JSON.
func Djson[t any](b io.ReadCloser, target *t) (*t, error) {
defer func() {
log.Info().Msg("closing")
_ = b.Close()
}()

err := json.NewDecoder(b).Decode(target)

if err != nil {
return nil, err
}
return target, nil
}

0 comments on commit 4e3dbd8

Please sign in to comment.