httpin icon indicating copy to clipboard operation
httpin copied to clipboard

bump version to 1.0.0

Open ggicci opened this issue 4 years ago • 5 comments

I'm planing to publish the first stable release of this program. If any of you were using this library in your production environment, please feel free to leave a comment below. A breif description of your application scenarios will bring great helps ❤️

ggicci avatar Oct 21 '21 15:10 ggicci

Hi, i'm looking at using your lib like this

package main

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

	"github.com/ggicci/httpin"
)

type Request[T any] struct {
	*http.Request
	Data *T
}

type Response[T any] struct {
	StatusCode int
	Data       *T
}

// Handler defines generic HTTP handler function.
type Handler[I, O any] func(*Request[I]) (*Response[O], error)

// Wrap wraps generic handler into Go idiomatic HTTP handler function.
// Request is parsed using [httpin.Decode].
// Response from generic handler is automatically JSON encoded and passed to idiomatic HTTP handler.
func Wrap[I, O any](handler Handler[I, O]) func(http.ResponseWriter, *http.Request) {
	return func(res http.ResponseWriter, req *http.Request) {
		var reqData I

		err := httpin.Decode(req, &reqData)
		if err != nil {
			return
		}

		r, err := handler(&Request[I]{Request: req, Data: &reqData})
		if err != nil {
			slog.Error("handler", "error", err)
			res.WriteHeader(http.StatusInternalServerError)
			return
		}
		render(res, r)
	}
}

func render[O any](res http.ResponseWriter, response *Response[O]) {
	res.Header().Set("Content-Type", "application/json")

	resData, err := json.Marshal(response.Data)
	if err != nil {
		res.WriteHeader(http.StatusInternalServerError)

		return
	}

	if response.StatusCode == 0 {
		response.StatusCode = http.StatusOK
	}

	res.WriteHeader(response.StatusCode)
	_, _ = res.Write(resData)
}

emilien-puget avatar Sep 05 '23 07:09 emilien-puget

Hi @emilien-puget , sorry I missed the message. But I still want to say thank you for your sharing your use case!

ggicci avatar Jan 14 '24 18:01 ggicci