Skip to content

Commit 752e2a3

Browse files
committed
fix(yaginmiddleware): manually handle request
1 parent a647fa9 commit 752e2a3

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

yaginmiddleware/rsa_secure.go

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,3 +319,62 @@ func (h *RSASecureHeader[T]) Handle(ctx *gin.Context) {
319319

320320
ctx.Next()
321321
}
322+
323+
// HandleRequest performs a one-shot RSA-secure header decoding operation,
324+
// similar to the middleware Handle(), but without invoking Gin’s middleware flow.
325+
//
326+
// Instead of calling `ctx.Next()` or aborting the request,
327+
// it simply reads the header, decrypts and decodes the payload,
328+
// updates the request header with the plaintext prefix (if present),
329+
// injects the decoded struct into the Gin context, and returns the
330+
// plaintext prefix, decoded struct, and error (if any).
331+
//
332+
// This function is intended for cases where you want to manually
333+
// process a secure header within a handler or service,
334+
// without globally applying middleware.
335+
//
336+
// The process:
337+
// 1. Reads the header specified in `HeaderName`.
338+
// 2. Strips CR/LF characters for safety.
339+
// 3. Calls Decode() to decrypt and deserialize the data.
340+
// 4. On success:
341+
// - Updates the original header to the plaintext prefix (if any).
342+
// - Stores the decoded struct in context under `ContextKey`.
343+
// - Returns plaintext prefix, decoded struct, and nil error.
344+
// 5. On failure:
345+
// - Returns empty string, nil data, and a wrapped yaerrors.Error.
346+
//
347+
// Example:
348+
//
349+
// type Payload struct {
350+
// Msg string
351+
// }
352+
//
353+
// key, _ := rsa.GenerateKey(rand.Reader, 2048)
354+
// header := yaginmiddleware.NewEncodeRSA[Payload]("X-Enc", "payload", key, true)
355+
//
356+
// r := gin.New()
357+
// r.GET("/decode", func(ctx *gin.Context) {
358+
// src, data, err := header.HandleRequest(ctx)
359+
// if err != nil {
360+
// ctx.String(http.StatusBadRequest, "decode error: %v", err)
361+
// return
362+
// }
363+
// fmt.Printf("Prefix: %s, Payload: %+v\n", src, data)
364+
// })
365+
func (h *RSASecureHeader[T]) HandleRequest(ctx *gin.Context) (string, *T, yaerrors.Error) {
366+
text := ctx.GetHeader(h.HeaderName)
367+
368+
text = yarsa.StripCRLF(text)
369+
370+
src, data, err := h.Decode(text)
371+
if err != nil {
372+
return "", nil, err.Wrap("[RSA HEADER] failed to decode statistic payload")
373+
}
374+
375+
ctx.Request.Header.Set(h.HeaderName, src)
376+
377+
ctx.Set(h.ContextKey, data)
378+
379+
return src, data, nil
380+
}

0 commit comments

Comments
 (0)