-
Notifications
You must be signed in to change notification settings - Fork 7
add http forwarder #29
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
bradstimpson
wants to merge
8
commits into
whosonfirst:main
Choose a base branch
from
bradstimpson:main
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 7 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
4788118
add http forwarder
bradstimpson 817c47b
add raw query
bradstimpson 873beb7
change to get query
bradstimpson 8ead4a3
stub out GET make POST default
bradstimpson 63a2fd7
formating fixes for error messages, rewrote HTTPDispatcher to move lo…
bradstimpson e501914
add error message on http destination not found
bradstimpson 9b019f0
further improved error messaging
bradstimpson b9675b5
modified based on PR comments
bradstimpson 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
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 |
---|---|---|
@@ -0,0 +1,132 @@ | ||
package dispatcher | ||
|
||
import ( | ||
"bytes" | ||
"context" | ||
"fmt" | ||
"io" | ||
"log" | ||
"net/http" | ||
"net/url" | ||
|
||
"github.com/whosonfirst/go-webhookd/v3" | ||
) | ||
|
||
func init() { | ||
|
||
ctx := context.Background() | ||
err := RegisterDispatcher(ctx, "http", NewHTTPDispatcher) | ||
thisisaaronland marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if err != nil { | ||
panic(err) | ||
} | ||
|
||
err = RegisterDispatcher(ctx, "https", NewHTTPDispatcher) | ||
if err != nil { | ||
panic(err) | ||
} | ||
} | ||
|
||
// GET and POST are the only supported HTTP methods | ||
const GET = "GET" | ||
const POST = "POST" | ||
|
||
// HTTPDispatcher implements the `webhookd.WebhookDispatcher` interface for dispatching messages to a `log.Logger` instance `http.get` or `http.post`. | ||
type HTTPDispatcher struct { | ||
webhookd.WebhookDispatcher | ||
// logger is the `log.Logger` instance associated with the dispatcher. | ||
logger *log.Logger | ||
// url to send the message to | ||
url url.URL | ||
// method to use when sending the message | ||
method string | ||
// client to use when sending the message | ||
client HTTPClient | ||
} | ||
|
||
// HTTPClient is an interface for `http.Client` to allow for mocking in tests. | ||
type HTTPClient interface { | ||
thisisaaronland marked this conversation as resolved.
Show resolved
Hide resolved
|
||
Get(url string) (*http.Response, error) | ||
Post(url string, contentType string, body io.Reader) (*http.Response, error) | ||
} | ||
|
||
// NewHTTPDispatcher returns a new `HTTPDispatcher` instance configured by 'uri' in the form of: | ||
// | ||
// http:// | ||
// https:// | ||
// | ||
// Messages are dispatched to the default `log.Default()` instance along with the uri parsed. | ||
func NewHTTPDispatcher(ctx context.Context, uri string) (webhookd.WebhookDispatcher, error) { | ||
logger := log.Default() | ||
|
||
parsed, err := url.Parse(uri) | ||
|
||
if err != nil { | ||
return nil, fmt.Errorf("Failed to parse URI, %w", err) | ||
} | ||
|
||
return NewHTTPDispatcherWithLogger(ctx, logger, *parsed, &http.Client{}) | ||
} | ||
|
||
// NewHTTPDispatcher returns a new `HTTPDispatcher` instance that dispatches messages to `http.Get` or `http.Post`. | ||
func NewHTTPDispatcherWithLogger(ctx context.Context, logger *log.Logger, url url.URL, client HTTPClient) (webhookd.WebhookDispatcher, error) { | ||
bradstimpson marked this conversation as resolved.
Show resolved
Hide resolved
|
||
display := fmt.Sprintf("%s://%s%s", url.Scheme, url.Host, url.Path) | ||
if len(url.Query()) > 0 { | ||
display += fmt.Sprintf("?%s", url.RawQuery) | ||
} | ||
logger.Print("Parsed dispatcher URL: ", display) | ||
bradstimpson marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
method := url.Query().Get("method") | ||
if method != GET { | ||
method = POST | ||
} | ||
|
||
d := HTTPDispatcher{ | ||
logger: logger, | ||
url: url, | ||
method: method, | ||
client: client, | ||
} | ||
|
||
return &d, nil | ||
} | ||
|
||
// Dispatch sends 'body' to the `log.Logger` and `http.Get`/`http.Post` that 'd' has been instantiated with. | ||
func (d *HTTPDispatcher) Dispatch(ctx context.Context, body []byte) *webhookd.WebhookError { | ||
var resp *http.Response | ||
var err error | ||
|
||
if d.method == GET { | ||
d.logger.Println("Dispatching GET:", d.url.String(), "not forwarding body: ", string(body)) | ||
resp, err = d.client.Get(d.url.String()) | ||
} else { | ||
d.logger.Println("Dispatching POST:", d.url.String(), "forwarding body: ", string(body)) | ||
resp, err = d.client.Post(d.url.String(), "application/json", bytes.NewBuffer(body)) | ||
} | ||
|
||
// if we get a nil response the destination is unreachable | ||
if resp == nil { | ||
code := http.StatusRequestTimeout | ||
message := "Timeout likely destination unreachable" | ||
whErr := &webhookd.WebhookError{Code: code, Message: message} | ||
return whErr | ||
} | ||
|
||
// if we get any other status code than 200 | ||
if resp.StatusCode != http.StatusOK { | ||
code := resp.StatusCode | ||
message := fmt.Sprintf("Failed to dispatch message: %s", resp.Status) | ||
whErr := &webhookd.WebhookError{Code: code, Message: message} | ||
return whErr | ||
} | ||
|
||
defer resp.Body.Close() | ||
bradstimpson marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
if err != nil { | ||
code := http.StatusInternalServerError | ||
message := err.Error() | ||
whErr := &webhookd.WebhookError{Code: code, Message: message} | ||
return whErr | ||
} | ||
|
||
return nil | ||
} |
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 |
---|---|---|
@@ -0,0 +1,71 @@ | ||
package dispatcher | ||
|
||
import ( | ||
"bytes" | ||
"context" | ||
"io" | ||
"io/ioutil" | ||
"log" | ||
"net/http" | ||
"net/url" | ||
"strings" | ||
"testing" | ||
) | ||
|
||
type MockHTTPClient struct { | ||
Resp *http.Response | ||
Error error | ||
} | ||
|
||
func (m *MockHTTPClient) Get(url string) (*http.Response, error) { | ||
return m.Resp, m.Error | ||
} | ||
|
||
func (m *MockHTTPClient) Post(url string, contentType string, body io.Reader) (*http.Response, error) { | ||
return m.Resp, m.Error | ||
} | ||
|
||
func TestNewHTTPDispatcherWithLogger(t *testing.T) { | ||
|
||
ctx := context.Background() | ||
|
||
var buf bytes.Buffer | ||
|
||
logger := log.New(&buf, "testing ", log.Lshortfile) | ||
|
||
parsed, err := url.Parse("http://testing?method=GET") | ||
if err != nil { | ||
t.Fatalf("Failed to parse url, %v", err) | ||
} | ||
|
||
// Create a mock response | ||
mockResponse := &http.Response{ | ||
StatusCode: http.StatusOK, | ||
Body: ioutil.NopCloser(strings.NewReader("Mock response body")), | ||
} | ||
|
||
// Create a mock HTTP client with the desired behavior | ||
mockClient := &MockHTTPClient{ | ||
Resp: mockResponse, | ||
Error: nil, | ||
} | ||
|
||
d, err := NewHTTPDispatcherWithLogger(ctx, logger, *parsed, mockClient) | ||
|
||
if err != nil { | ||
t.Fatalf("Failed to create new http dispatcher with logger, %v", err) | ||
} | ||
|
||
err2 := d.Dispatch(ctx, []byte("hello world")) | ||
|
||
if err2 != nil { | ||
t.Fatalf("Failed to dispatch message, %v", err2) | ||
} | ||
|
||
expected := "testing http.go:76: Parsed dispatcher URL: http://testing?method=GET\ntesting http.go:99: Dispatching GET: http://testing?method=GET not forwarding body: hello world" | ||
output := strings.TrimSpace(buf.String()) | ||
|
||
if output != expected { | ||
t.Fatalf("Unexpected output from custom writer: '%s'", output) | ||
} | ||
} |
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 |
---|---|---|
@@ -0,0 +1 @@ | ||
checks = ["all", "-ST1005", "-ST1003", "-ST1020","-ST1021"] |
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.