Skip to content

Commit

Permalink
add request to deprecate hook
Browse files Browse the repository at this point in the history
  • Loading branch information
LukasJenicek committed Sep 26, 2024
1 parent 430da64 commit 463d1c8
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
7 changes: 7 additions & 0 deletions helpers.go.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ var (
ServiceNameCtxKey = &contextKey{"ServiceName"}

MethodNameCtxKey = &contextKey{"MethodName"}

AnnotationsCtxKey = &contextKey{"Annotations"}
)

func ServiceNameFromContext(ctx context.Context) string {
Expand All @@ -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)
Expand Down
23 changes: 18 additions & 5 deletions server.go.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -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}} {
Expand All @@ -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:
Expand Down

0 comments on commit 463d1c8

Please sign in to comment.