func()

in openwhisk/forward_proxy.go [122:186]


func (ap *ActionProxy) ForwardInitRequest(w http.ResponseWriter, r *http.Request) {
	var initRequest initRequest
	err := json.NewDecoder(r.Body).Decode(&initRequest)
	if err != nil {
		sendError(w, http.StatusBadRequest, fmt.Sprintf("Error decoding init body while forwarding request: %v", err))
		return
	}

	Debug("Decoded init request: len: %d - main: %s", r.ContentLength, initRequest.Value.Main)
	proxyData, err := parseMainFlag(initRequest.Value.Main)
	if err != nil {
		sendError(w, http.StatusBadRequest, err.Error())
		return
	}

	// set the proxy data
	ap.clientProxyData = proxyData
	ap.clientProxyData.ProxyActionID = uuid.New().String()

	newBody := initRequest
	newBody.Value.Main = ap.clientProxyData.MainFunc
	newBody.ProxiedActionID = ap.clientProxyData.ProxyActionID

	codeHash := calculateCodeHash(initRequest.Value.Code)
	if newBody.Value.Env == nil {
		newBody.Value.Env = make(map[string]interface{})
	}
	newBody.Value.Env[OW_CODE_HASH] = codeHash
	ap.clientProxyData.ActionCodeHash = codeHash
	Debug("Set code hash: %s", codeHash)

	var buf bytes.Buffer
	err = json.NewEncoder(&buf).Encode(newBody)
	if err != nil {
		sendError(w, http.StatusBadRequest, fmt.Sprintf("Error encoding updated init body: %v", err))
		return
	}

	bodyLen := buf.Len()
	r.Body = io.NopCloser(bytes.NewBuffer(buf.Bytes()))

	director := func(req *http.Request) {
		req.Header = r.Header.Clone()

		// Reset content length with the new body
		req.Header.Set("Content-Length", strconv.Itoa(bodyLen))
		req.ContentLength = int64(bodyLen)

		req.URL.Scheme = ap.clientProxyData.ProxyURL.Scheme
		req.URL.Host = ap.clientProxyData.ProxyURL.Host
		req.Host = ap.clientProxyData.ProxyURL.Host
	}

	proxy := &httputil.ReverseProxy{Director: director}
	proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
		Debug("Error forwarding init request: %v", err)
		sendError(w, http.StatusBadGateway, "Error forwarding init request. Check logs for details.")
	}

	Debug("Forwarding init request to %s", ap.clientProxyData.ProxyURL.String())
	proxy.ServeHTTP(w, r)
	if f, ok := w.(http.Flusher); ok {
		f.Flush()
	}
}