11package tools
22
33import (
4+ "fmt"
5+ "io/ioutil"
46 "log"
57 "net/http"
68 "net/http/httputil"
79 "net/url"
10+ "strconv"
811 "strings"
912)
1013
@@ -30,8 +33,40 @@ func ProxyResponseHandler() func(*http.Response) error {
3033 return func (r * http.Response ) error {
3134 log .Printf ("RES: %s \" %s\" %d \" %s\" \" %s\" " , r .Request .RemoteAddr , r .Request .Method , r .StatusCode , r .Request .RequestURI , r .Request .UserAgent ())
3235
36+ contentType := r .Header .Get ("Content-Type" )
37+ log .Printf ("%s" , contentType )
38+
39+ // Do some quick fixes to the HTTP response for NPM install requests
40+ // TODO: Get this actually working, it looks like the JSON responses provide the correct URLs via CURL, but not when using npm against it.
41+ if strings .HasPrefix (r .Request .UserAgent (), "npm" ) {
42+ if ! strings .Contains (contentType , "application/json" ) {
43+ return nil
44+ }
45+
46+ // replace any instances of the CodeArtifact URL with the local URL
47+ oldContentResponse , _ := ioutil .ReadAll (r .Body )
48+ oldContentResponseStr := string (oldContentResponse )
49+
50+ u , _ := url .Parse (CodeArtifactAuthInfo .Url )
51+ hostname := u .Host + ":443"
52+
53+ resolvedHostname := strings .Replace (CodeArtifactAuthInfo .Url , u .Host , hostname , - 1 )
54+ newUrl := fmt .Sprintf ("http://%s/" , "localhost" )
55+ log .Printf ("URI conversion %s -> %s" , resolvedHostname , newUrl )
56+
57+ newResponseContent := strings .Replace (oldContentResponseStr , resolvedHostname , newUrl , - 1 )
58+ newResponseContent = strings .Replace (newResponseContent , CodeArtifactAuthInfo .Url , newUrl , - 1 )
59+
60+ log .Print (newResponseContent )
61+
62+ r .Body = ioutil .NopCloser (strings .NewReader (newResponseContent ))
63+ r .ContentLength = int64 (len (newResponseContent ))
64+ r .Header .Set ("Content-Length" , strconv .Itoa (len (newResponseContent )))
65+ }
66+
3367 return nil
3468 }
69+
3570}
3671
3772// ProxyInit initialises the CodeArtifact proxy and starts the HTTP listener
0 commit comments