Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bump version to 1.0.0 #7

Open
ggicci opened this issue Oct 21, 2021 · 2 comments
Open

bump version to 1.0.0 #7

ggicci opened this issue Oct 21, 2021 · 2 comments
Labels
help wanted Extra attention is needed

Comments

@ggicci
Copy link
Owner

ggicci commented Oct 21, 2021

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 ggicci added the help wanted Extra attention is needed label Oct 21, 2021
@ggicci ggicci changed the title Bump version to 1.0.0 bump version to 1.0.0 Apr 16, 2022
@emilien-puget
Copy link

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)
}

@ggicci
Copy link
Owner Author

ggicci commented Jan 14, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

2 participants