good morning!!!!

Skip to content
Snippets Groups Projects
handler.go 871 B
Newer Older
a's avatar
a committed
package http

import (
Garet Halliday's avatar
Garet Halliday committed
	"context"
	"errors"
a's avatar
a committed
	"net/http"
a's avatar
a committed

a's avatar
a committed
	"golang.org/x/net/http2"
	"golang.org/x/net/http2/h2c"
Garet Halliday's avatar
Garet Halliday committed

a's avatar
a committed
	"gfx.cafe/open/jrpc/pkg/jsonrpc"
Garet Halliday's avatar
Garet Halliday committed
	"gfx.cafe/open/jrpc/pkg/server"
a's avatar
a committed
)

a's avatar
a committed
func JrpcToHttp(h jsonrpc.Handler) http.Handler {
	return HttpHandler(server.NewServer(h))
}

a's avatar
a committed
func HttpHandler(s *server.Server) http.Handler {
a's avatar
a committed
	return h2c.NewHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if s == nil {
			http.Error(w, "no server set", http.StatusInternalServerError)
			return
		}
		c, err := NewCodec(w, r)
		if err != nil {
			return
		}
		w.Header().Set("content-type", contentType)
		err = s.ServeCodec(r.Context(), c)
		if err != nil && !errors.Is(err, context.Canceled) {
			//  slog.Error("codec err", "err", err)
			http.Error(w, "Internal Error", http.StatusInternalServerError)
			return
		}
		<-c.Closed()
	}), &http2.Server{})
a's avatar
a committed
}