Skip to content

Commit

Permalink
add webrpc ctx containing multiple ctx values
Browse files Browse the repository at this point in the history
  • Loading branch information
LukasJenicek committed Sep 27, 2024
1 parent 1af2de2 commit 20a35c5
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 3 deletions.
23 changes: 22 additions & 1 deletion _examples/golang-basics/example.gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 23 additions & 1 deletion _examples/golang-imports/api.gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 15 additions & 1 deletion helpers.go.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ func (k *contextKey) String() string {
return "webrpc context value " + k.name
}

type WebRrpCtx struct {
ServiceName string
Request *http.Request
Annotations map[string]string
Writer http.ResponseWriter
}

var (
{{- if $opts.client}}
HTTPClientRequestHeadersCtxKey = &contextKey{"HTTPClientRequestHeaders"}
Expand All @@ -28,6 +35,8 @@ var (
MethodNameCtxKey = &contextKey{"MethodName"}

MethodAnnotationsCtxKey = &contextKey{"MethodAnnotations"}

WebRpcCtxKey = &contextKey{"WebRPC"}
)

func ServiceNameFromContext(ctx context.Context) string {
Expand All @@ -50,7 +59,12 @@ func MethodAnnotationsFromContext(ctx context.Context) map[string]string {
return annotations
}

{{- if $opts.server}}
func WebRPCContext(ctx context.Context) map[string]string {
annotations, _ := ctx.Value(MethodAnnotationsCtxKey).(map[string]string)
return annotations
}

{{if $opts.server}}
func ResponseWriterFromContext(ctx context.Context) http.ResponseWriter {
w, _ := ctx.Value(HTTPResponseWriterCtxKey).(http.ResponseWriter)
return w
Expand Down
6 changes: 6 additions & 0 deletions server.go.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ func (s *{{$serviceName}}) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx = context.WithValue(ctx, HTTPRequestCtxKey, r)
ctx = context.WithValue(ctx, ServiceNameCtxKey, "{{.Name}}")
ctx = context.WithValue(ctx, MethodAnnotationsCtxKey, methodAnnotations[r.URL.Path])
ctx = context.WithValue(ctx, WebRpcCtxKey, &WebRrpCtx{
Annotations: methodAnnotations[r.URL.Path],
Request: r,
ServiceName: "{{.Name}}",
Writer: w,
})

if s.OnRequest != nil {
s.OnRequest(w, r)
Expand Down

0 comments on commit 20a35c5

Please sign in to comment.