a repo to hold some common helpers

Stephen Searles 2 weeks ago
commit 7d5bf482a0
  1. 11
      shttp/LICENSE
  2. 3
      shttp/go.mod
  3. 135
      shttp/handlers.go

@ -0,0 +1,11 @@
Copyright 2025 Stephen Searles
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

@ -0,0 +1,3 @@
module git.stephensearles.com/stephen/scom/shttp
go 1.24.0

@ -0,0 +1,135 @@
package shttp
import (
"bufio"
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
)
type ctxKeyReq struct{}
func WithRequest(ctx context.Context, r *http.Request) context.Context {
return context.WithValue(ctx, ctxKeyReq{}, r)
}
func RequestFromContext(ctx context.Context) *http.Request {
r, _ := ctx.Value(ctxKeyReq{}).(*http.Request)
return r
}
// JSONHandler serves a JSON request with a JSON response.
type JSONHandler[TReq any, TResp any] struct {
BodyOptional bool
Handler func(context.Context, TReq) (TResp, error)
ErrHandler func(http.ResponseWriter, *http.Request, string, error)
}
func (j JSONHandler[TReq, TResp]) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx = WithRequest(ctx, r)
body := new(TReq)
bodyBuf := bufio.NewReader(r.Body)
if _, err := bodyBuf.Peek(1); err != nil {
if !errors.Is(err, io.EOF) {
j.handleErr(w, r, "reading request", err, http.StatusBadRequest)
return
}
if !j.BodyOptional {
j.handleErr(w, r, "missing request body", err, http.StatusBadRequest)
return
}
}
err := json.NewDecoder(bodyBuf).Decode(body)
if err != nil {
j.handleErr(w, r, "decoding json request", err, http.StatusBadRequest)
return
}
resp, err := j.Handler(ctx, *body)
if err != nil {
j.handleErr(w, r, "handling request", err, http.StatusInternalServerError)
return
}
err = json.NewEncoder(w).Encode(resp)
if err != nil {
j.handleErr(w, r, "serving response", err, 0)
return
}
}
func (j JSONHandler[TReq, TResp]) handleErr(w http.ResponseWriter, r *http.Request, op string, err error, defaultStatus int) {
if j.ErrHandler != nil {
j.ErrHandler(w, r, op, err)
return
}
if defaultStatus > 0 {
w.WriteHeader(defaultStatus)
}
slog.WarnContext(r.Context(), op, "err", err)
}
// HTMLHandler serves a request with an HTML response.
type HTMLHandler[TReq any, TResp any] struct {
BodyOptional bool
Handler func(context.Context, TReq) (TResp, error)
ErrHandler func(http.ResponseWriter, *http.Request, string, error)
}
func (j HTMLHandler[TReq, TResp]) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
body := new(TReq)
bodyBuf := bufio.NewReader(r.Body)
if _, err := bodyBuf.Peek(1); err != nil {
if !errors.Is(err, io.EOF) {
j.handleErr(w, r, "decoding json request", err)
return
}
if !j.BodyOptional {
j.handleErr(w, r, "missing request body", err)
return
}
}
err := json.NewDecoder(bodyBuf).Decode(body)
if err != nil {
j.handleErr(w, r, "decoding json request", err)
return
}
resp, err := j.Handler(ctx, *body)
if err != nil {
j.handleErr(w, r, "handling request", err)
return
}
err = json.NewEncoder(w).Encode(resp)
if err != nil {
j.handleErr(w, r, "serving response", err)
return
}
}
func (j HTMLHandler[TReq, TResp]) handleErr(w http.ResponseWriter, r *http.Request, op string, err error) {
if j.ErrHandler != nil {
j.ErrHandler(w, r, op, err)
return
}
slog.WarnContext(r.Context(), op, "err", err)
}
Loading…
Cancel
Save