Skip to content

Commit

Permalink
Fix error handling in ecs server
Browse files Browse the repository at this point in the history
  • Loading branch information
mtibben committed Apr 20, 2020
1 parent 4fceeef commit 591a63b
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 7 deletions.
2 changes: 1 addition & 1 deletion server/ec2.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ func startEc2CredentialsServer(creds *credentials.Credentials, region string) {

router.HandleFunc("/latest/meta-data/iam/security-credentials/local-credentials", credsHandler(creds))

log.Fatalln(http.ListenAndServe(ec2CredentialsServerAddr, logRequest(withLoopbackSecurityCheck(router))))
log.Fatalln(http.ListenAndServe(ec2CredentialsServerAddr, withLogging(withLoopbackSecurityCheck(router))))
}

// withLoopbackSecurityCheck is middleware to check that the request comes from the loopback device
Expand Down
11 changes: 6 additions & 5 deletions server/ecs.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@ import (
"github.com/aws/aws-sdk-go/aws/credentials"
)

func writeErrorMessage(w http.ResponseWriter, msg string, status int) {
err := json.NewEncoder(w).Encode(map[string]string{"Message": msg})
if err != nil {
http.Error(w, err.Error(), status)
func writeErrorMessage(w http.ResponseWriter, msg string, statusCode int) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(statusCode)
if err := json.NewEncoder(w).Encode(map[string]string{"Message": msg}); err != nil {
log.Println(err.Error())
}
}

Expand All @@ -41,7 +42,7 @@ func StartEcsCredentialServer(creds *credentials.Credentials) (string, string, e
}

go func() {
err := http.Serve(listener, logRequest(withAuthorizationCheck(token, ecsCredsHandler(creds))))
err := http.Serve(listener, withLogging(withAuthorizationCheck(token, ecsCredsHandler(creds))))
// returns ErrServerClosed on graceful close
if err != http.ErrServerClosed {
log.Fatalf("ecs server: %s", err.Error())
Expand Down
2 changes: 1 addition & 1 deletion server/httplog.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ func (w *loggingMiddlewareResponseWriter) WriteHeader(statusCode int) {
w.ResponseWriter.WriteHeader(statusCode)
}

func logRequest(handler http.Handler) http.Handler {
func withLogging(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestStart := time.Now()
w2 := &loggingMiddlewareResponseWriter{w, http.StatusOK}
Expand Down

0 comments on commit 591a63b

Please sign in to comment.