From 463d1c8080f9c651012634b154fda7eac8cfa3ba Mon Sep 17 00:00:00 2001 From: Lukas Jenicek Date: Thu, 26 Sep 2024 10:32:34 +0200 Subject: [PATCH] add request to deprecate hook --- helpers.go.tmpl | 7 +++++++ server.go.tmpl | 23 ++++++++++++++++++----- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/helpers.go.tmpl b/helpers.go.tmpl index c743309..e0a1ba1 100644 --- a/helpers.go.tmpl +++ b/helpers.go.tmpl @@ -26,6 +26,8 @@ var ( ServiceNameCtxKey = &contextKey{"ServiceName"} MethodNameCtxKey = &contextKey{"MethodName"} + + AnnotationsCtxKey = &contextKey{"Annotations"} ) func ServiceNameFromContext(ctx context.Context) string { @@ -43,6 +45,11 @@ func RequestFromContext(ctx context.Context) *http.Request { return r } +func AnnotationsFromContext(ctx context.Context) map[string]string { + annotations, _ := ctx.Value(AnnotationsCtxKey).(map[string]string) + return annotations +} + {{- if $opts.server}} func ResponseWriterFromContext(ctx context.Context) http.ResponseWriter { w, _ := ctx.Value(HTTPResponseWriterCtxKey).(http.ResponseWriter) diff --git a/server.go.tmpl b/server.go.tmpl index 1213828..f928446 100644 --- a/server.go.tmpl +++ b/server.go.tmpl @@ -17,10 +17,22 @@ type WebRPCServer interface { {{- $name := $service.Name -}} {{ $serviceName := (printf "%sServer" (firstLetterToLower $service.Name)) }} +var ( + annotations = map[string]map[string]string{ + {{- range $_, $method := $service.Methods}} + "/rpc/{{$name}}/{{$method.Name}}": { + {{- range $_, $annotation := $method.Annotations -}} + "{{$annotation.AnnotationType}}": "{{$annotation.Value}}", + {{- end -}} + }, + {{- end -}} + } +) + type {{$serviceName}} struct { {{$typePrefix}}{{$service.Name}} OnError func(r *http.Request, rpcErr *WebRPCError) - OnDeprecate func(endpoint string, newEndpoint string) + OnRequest func(w http.ResponseWriter, r *http.Request) } func New{{firstLetterToUpper $service.Name}}Server(svc {{$typePrefix}}{{.Name}}) *{{$serviceName}} { @@ -42,15 +54,16 @@ func (s *{{$serviceName}}) ServeHTTP(w http.ResponseWriter, r *http.Request) { ctx = context.WithValue(ctx, HTTPResponseWriterCtxKey, w) ctx = context.WithValue(ctx, HTTPRequestCtxKey, r) ctx = context.WithValue(ctx, ServiceNameCtxKey, "{{.Name}}") + ctx = context.WithValue(ctx, AnnotationsCtxKey, annotations[r.URL.Path]) + + if s.OnRequest != nil { + s.OnRequest(w, r) + } var handler func(ctx context.Context, w http.ResponseWriter, r *http.Request) switch r.URL.Path { {{- range $_, $method := $service.Methods}} case "/rpc/{{$name}}/{{$method.Name}}": - {{- $deprecated := $method.Annotations.Deprecated -}} - {{- if $deprecated -}} - s.OnDeprecate("{{ $method.Name }}", "{{ index $deprecated.Args 0 }}") - {{- end}} handler = s.serve{{$method.Name | firstLetterToUpper}}JSON{{if $method.StreamOutput}}Stream{{end}} {{- end}} default: