package route import ( "context" "encoding/json" "net/http" "sectorinf.com/emilis/fupie/logie" ) type Keeper struct { Status int } type ResponseWriterKeeper struct { http.ResponseWriter Keeper } func (r *ResponseWriterKeeper) WriteHeader(status int) { r.Status = status r.ResponseWriter.WriteHeader(status) } type Context struct { Writer http.ResponseWriter Request *http.Request Context context.Context Log logie.Log } func (c Context) JSON(v any) { c.JSONStatus(http.StatusOK, v) } func (c Context) JSONStatus(status int, v any) { data, err := json.Marshal(v) if err != nil { c.Log.Errorf("json marshal: %s", err.Error()) c.Writer.WriteHeader(http.StatusInternalServerError) return } c.Writer.WriteHeader(status) c.Writer.Header().Set("Content-Type", "application/json") c.Writer.Write(data) } func (c Context) Status(status int) { c.Writer.WriteHeader(status) c.Writer.Write([]byte(http.StatusText(status))) } func (c Context) InternalServerError(args ...any) { c.Log.Error(args...) c.Writer.WriteHeader(http.StatusInternalServerError) } func (c Context) InternalServerErrorf(format string, args ...any) { c.Log.Errorf(format, args...) c.Writer.WriteHeader(http.StatusInternalServerError) } func (c Context) DataStatus(status int, data []byte) { c.DataStatusType(status, http.DetectContentType(data), data) } func (c Context) Data(data []byte) { c.DataStatus(http.StatusOK, data) } func (c Context) DataStatusType(status int, contentType string, data []byte) { c.Writer.Header().Set("Content-Type", contentType) c.Writer.WriteHeader(status) c.Writer.Write(data) } func (c Context) SeeOther(uri string) { http.Redirect(c.Writer, c.Request, uri, http.StatusSeeOther) }