Skip to content

Commit

Permalink
Add content-type to header2body plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
Kyaw Myint Thein committed Oct 12, 2021
1 parent 71640cd commit cbecc45
Showing 1 changed file with 35 additions and 21 deletions.
56 changes: 35 additions & 21 deletions header2body.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package rzluramartian
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"

Expand All @@ -12,10 +13,12 @@ import (
type (
HeaderModifierConfig struct {
KeysToExtract []string `json:"keys_to_extract"`
ContentType string `json:"content_type"`
}

Header2BodyModifier struct {
keysToExtract []string
ContentType string
}
)

Expand All @@ -27,44 +30,55 @@ func headerModifierFromJSON(b []byte) (*parse.Result, error) {

mod := &Header2BodyModifier{
keysToExtract: cfg.KeysToExtract,
ContentType: cfg.ContentType,
}
return parse.NewResult(mod, []parse.ModifierType{parse.Request})
}

func (m *Header2BodyModifier) ModifyRequest(req *http.Request) error {
var buf []byte

if req.Body != nil {
body, err := ioutil.ReadAll(req.Body)
if err != nil {
return err
}

data := make(map[string]interface{})
err = json.Unmarshal(body, &data)
if err != nil {
return err
}
switch m.ContentType {
case _contentType_applicationJSON:
data := make(map[string]interface{})
json.Unmarshal(body, &data) // Skip error even if it is failed

for _, k := range m.keysToExtract {
data[k] = req.Header.Get(k)
req.Header.Del(k)
}
for _, k := range m.keysToExtract {
data[k] = req.Header.Get(k)
req.Header.Del(k)
}

buf, err = json.Marshal(data)
if err != nil {
return err
buf, err = json.Marshal(data)
if err != nil {
return err
}
default:
return fmt.Errorf("unsupport content-type")
}

} else {
data := make(map[string]interface{})
for _, k := range m.keysToExtract {
data[k] = req.Header.Get(k)
req.Header.Del(k)
}
switch m.ContentType {
case _contentType_applicationJSON:
data := make(map[string]interface{})

var err error
buf, err = json.Marshal(data)
if err != nil {
return err
for _, k := range m.keysToExtract {
data[k] = req.Header.Get(k)
req.Header.Del(k)
}

var err error
buf, err = json.Marshal(data)
if err != nil {
return err
}
default:
return fmt.Errorf("unsupport content-type")
}
}
req.ContentLength = int64(len(buf))
Expand Down

0 comments on commit cbecc45

Please sign in to comment.