-
Notifications
You must be signed in to change notification settings - Fork 101
Add support for templating in response bodies #177
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
deerbone
wants to merge
10
commits into
friendsofgo:main
Choose a base branch
from
deerbone:feature/templating
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
94875bb
Add support for templating in response bodies
deerbone 2fa497a
Edit README.md
deerbone 3ad1631
extend templating with useful functions
deerbone 2466739
fix README.md
deerbone cd95984
use jsonc in code blocks
deerbone c74d9e2
Update README.md
deerbone e552b0d
Update README.md
deerbone 8926a98
Update internal/server/http/handler_test.go
deerbone 2f9a63a
Update internal/server/http/handler_test.go
deerbone b934ff5
refactor templating with added tests
deerbone File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,11 +1,17 @@ | ||
| package http | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "encoding/json" | ||
| "fmt" | ||
| "io" | ||
| "log" | ||
| "net/http" | ||
| "os" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/friendsofgo/killgrave/internal/templating" | ||
| ) | ||
|
|
||
| // ImposterHandler create specific handler for the received imposter | ||
|
|
@@ -17,7 +23,7 @@ func ImposterHandler(i Imposter) http.HandlerFunc { | |
| } | ||
| writeHeaders(res, w) | ||
| w.WriteHeader(res.Status) | ||
| writeBody(i, res, w) | ||
| writeBody(i, res, w, r) | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -31,27 +37,122 @@ func writeHeaders(r Response, w http.ResponseWriter) { | |
| } | ||
| } | ||
|
|
||
| func writeBody(i Imposter, r Response, w http.ResponseWriter) { | ||
| wb := []byte(r.Body) | ||
| func writeBody(i Imposter, res Response, w http.ResponseWriter, r *http.Request) { | ||
| bodyBytes := []byte(res.Body) | ||
|
|
||
| if res.BodyFile != nil { | ||
| bodyFile := i.CalculateFilePath(*res.BodyFile) | ||
| bodyBytes = fetchBodyFromFile(bodyFile) | ||
| } | ||
|
|
||
| bodyStr := string(bodyBytes) | ||
|
|
||
| // early return if body does not contain templating | ||
| if !strings.Contains(bodyStr, "{{") { | ||
| w.Write([]byte(bodyStr)) | ||
| return | ||
| } | ||
|
|
||
| structuredBody, err := extractBody(r) | ||
| if err != nil { | ||
| log.Printf("error extracting body: %v\n", err) | ||
| } | ||
|
|
||
| templData := templating.TemplatingData{ | ||
| RequestBody: structuredBody, | ||
| PathParams: extractPathParams(r, i.Request.Endpoint), | ||
| QueryParams: extractQueryParams(r), | ||
| } | ||
|
|
||
| if r.BodyFile != nil { | ||
| bodyFile := i.CalculateFilePath(*r.BodyFile) | ||
| wb = fetchBodyFromFile(bodyFile) | ||
| templateBytes, err := templating.ApplyTemplate(bodyStr, templData) | ||
| if err != nil { | ||
| log.Printf("error applying template: %v\n", err) | ||
| } | ||
| w.Write(wb) | ||
|
|
||
| w.Write(templateBytes) | ||
| } | ||
|
|
||
| func fetchBodyFromFile(bodyFile string) (bytes []byte) { | ||
| func fetchBodyFromFile(bodyFile string) []byte { | ||
| if _, err := os.Stat(bodyFile); os.IsNotExist(err) { | ||
| log.Printf("the body file %s not found\n", bodyFile) | ||
| return | ||
| return nil | ||
| } | ||
|
|
||
| f, _ := os.Open(bodyFile) | ||
| defer f.Close() | ||
| bytes, err := io.ReadAll(f) | ||
| if err != nil { | ||
| log.Printf("imposible read the file %s: %v\n", bodyFile, err) | ||
| return nil | ||
| } | ||
| return bytes | ||
| } | ||
|
|
||
| func extractBody(r *http.Request) (map[string]interface{}, error) { | ||
| body := make(map[string]interface{}) | ||
| if r.Body == http.NoBody { | ||
| return body, nil | ||
| } | ||
|
|
||
| bodyBytes, err := io.ReadAll(r.Body) | ||
| if err != nil { | ||
| return body, fmt.Errorf("error reading request body: %w", err) | ||
| } | ||
|
|
||
| // Restore the body for further use | ||
| r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) | ||
|
|
||
| contentType := r.Header.Get("Content-Type") | ||
|
|
||
| switch { | ||
| case strings.Contains(contentType, "application/json"): | ||
| err = json.Unmarshal(bodyBytes, &body) | ||
| default: | ||
| return body, fmt.Errorf("unsupported content type: %s", contentType) | ||
| } | ||
|
|
||
| if err != nil { | ||
| return body, fmt.Errorf("error unmarshaling request body: %w", err) | ||
| } | ||
|
|
||
| return body, nil | ||
| } | ||
|
|
||
| func extractPathParams(r *http.Request, endpoint string) map[string]string { | ||
| params := make(map[string]string) | ||
|
|
||
| path := r.URL.Path | ||
| if path == "" { | ||
| return params | ||
| } | ||
|
|
||
| // split path and endpoint by / | ||
| pathParts := strings.Split(path, "/") | ||
| endpointParts := strings.Split(endpoint, "/") | ||
|
|
||
| if len(pathParts) != len(endpointParts) { | ||
| log.Printf("request path and endpoint parts do not match: %s, %s\n", path, endpoint) | ||
| return params | ||
| } | ||
|
|
||
| // iterate over pathParts and endpointParts | ||
| for i := range endpointParts { | ||
| if strings.HasPrefix(endpointParts[i], ":") { | ||
| params[endpointParts[i][1:]] = pathParts[i] | ||
| } | ||
| if strings.HasPrefix(endpointParts[i], "{") && strings.HasSuffix(endpointParts[i], "}") { | ||
| params[endpointParts[i][1:len(endpointParts[i])-1]] = pathParts[i] | ||
| } | ||
| } | ||
|
|
||
| return params | ||
| } | ||
|
|
||
| func extractQueryParams(r *http.Request) map[string][]string { | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Also for this one, please 🙏🏻 |
||
| params := make(map[string][]string) | ||
| query := r.URL.Query() | ||
| for k, v := range query { | ||
| params[k] = v | ||
| } | ||
| return | ||
| return params | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.