I am making a fire and forget micro-service that accepts http POST requests and gathers the needed data from the request body which it then requests to the given URL in the body.
The issue I'm having is that the numbers of headers in the input data is dynamic, meaning that there can be 1 or more headers. It differs.
I therefor read Unmarshal the incoming requestBody to the following struct:
type Request struct {
Headers json.RawMessage `json:"headers"`
Method string `json:"method"`
Body json.RawMessage `json:"body"`
}
type Event struct {
Url string `json:"url"`
Request Request `json:"request"`
}
with:
var newEvent Event
reqBody, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Fprintln(w, err)
}
err2 := json.Unmarshal(reqBody, &newEvent)
if err2 != nil {
fmt.Fprintln(w, err2)
}
The body is easy to just pass on when creating the request:
req, err := http.NewRequest(newEvent.Request.Method , newEvent.Url, bytes.NewBuffer(newEvent.Request.Body))
if err != nil {
panic(err)
}
But when setting the headers I can't find any nifty way to just pass the json.RawMessage format. Optimally I would just like to do something like this:
req.Header = http.Header{newEvent.Request.Headers}
Is there any smart solution for this or do I have to opt to Unmarshalling the headers to a string and then parsing the sting and add them all with http.Header.Add()
?
CodePudding user response:
Is there any smart solution for this [...]
No.
[...] or do I have to opt to Unmarshalling the headers to a string and then parsing the sting and add them all with http.Header.Add()?
Yes.
(Except you redesign your input and get rid of the json.RawMessage.)
In general there are no shortcuts, no clever hacks, magic beans or syntactic sugar in Go to avoid some code.