Files
paralus/pkg/gateway/gateway.go
nirav-rafay c66bdc25cd restructure rcloud-base as a single base controller (#37)
* restructure rcloud-base as a single base controller
* updated master.rest
* moved sentry from internal to pkg as it is used by relay
* removing unused rpc and it's dependencies
* Fix usermgmt tests
* Don't redefine variables in rest file
Co-authored-by: Abin Simon <abin.simon@rafay.co>
2022-03-03 17:59:06 +05:30

49 lines
1.3 KiB
Go

package gateway
import (
"context"
"errors"
"net/http"
"google.golang.org/grpc"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
)
// ErrNoHandlers returned when not handlers are passed to gateway
var ErrNoHandlers = errors.New("no handlers defined")
// HandlerFromEndpoint defines the function for registering grpc gateway handlers to grpc endpoint
type HandlerFromEndpoint func(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error)
// NewGateway returns new grpc gateway
func NewGateway(ctx context.Context, endpoint string, serveMuxOptions []runtime.ServeMuxOption, handlers ...HandlerFromEndpoint) (http.Handler, error) {
rafayJSON := NewRafayJSON()
rafayYAML := NewRafayYAML()
httpBody := NewHTTPBodyMarshaler()
serveMuxOptions = append(serveMuxOptions,
runtime.WithMarshalerOption(runtime.MIMEWildcard, httpBody),
runtime.WithMarshalerOption(jsonContentType, rafayJSON),
runtime.WithMarshalerOption(yamlContentType, rafayYAML),
runtime.WithMetadata(rafayGatewayAnnotator),
)
mux := runtime.NewServeMux(serveMuxOptions...)
if len(handlers) < 1 {
return nil, ErrNoHandlers
}
opts := []grpc.DialOption{grpc.WithInsecure()}
for _, handler := range handlers {
err := handler(ctx, mux, endpoint, opts)
if err != nil {
return nil, err
}
}
return mux, nil
}