github.com/TeaOSLab/EdgeNode@v1.3.8/internal/nodes/http_request_url.go (about)

     1  package nodes
     2  
     3  import (
     4  	"github.com/TeaOSLab/EdgeNode/internal/remotelogs"
     5  	"github.com/TeaOSLab/EdgeNode/internal/utils"
     6  	"github.com/iwind/TeaGo/logs"
     7  	"io"
     8  	"net/http"
     9  	"time"
    10  )
    11  
    12  // 请求某个URL
    13  func (this *HTTPRequest) doURL(method string, url string, host string, statusCode int, supportVariables bool) {
    14  	req, err := http.NewRequest(method, url, this.RawReq.Body)
    15  	if err != nil {
    16  		logs.Error(err)
    17  		return
    18  	}
    19  
    20  	// 修改Host
    21  	if len(host) > 0 {
    22  		req.Host = this.Format(host)
    23  	}
    24  
    25  	// 添加当前Header
    26  	req.Header = this.RawReq.Header
    27  
    28  	// 代理头部
    29  	this.setForwardHeaders(req.Header)
    30  
    31  	// 自定义请求Header
    32  	this.processRequestHeaders(req.Header)
    33  
    34  	var client = utils.SharedHttpClient(60 * time.Second)
    35  	resp, err := client.Do(req)
    36  	if err != nil {
    37  		remotelogs.Error("HTTP_REQUEST_URL", req.URL.String()+": "+err.Error())
    38  		this.write50x(err, http.StatusInternalServerError, "Failed to read url", "读取URL失败", false)
    39  		return
    40  	}
    41  	defer func() {
    42  		_ = resp.Body.Close()
    43  	}()
    44  
    45  	// Header
    46  	if statusCode <= 0 {
    47  		this.ProcessResponseHeaders(this.writer.Header(), resp.StatusCode)
    48  	} else {
    49  		this.ProcessResponseHeaders(this.writer.Header(), statusCode)
    50  	}
    51  
    52  	if supportVariables {
    53  		resp.Header.Del("Content-Length")
    54  	}
    55  	this.writer.AddHeaders(resp.Header)
    56  	if statusCode <= 0 {
    57  		this.writer.Prepare(resp, resp.ContentLength, resp.StatusCode, true)
    58  	} else {
    59  		this.writer.Prepare(resp, resp.ContentLength, statusCode, true)
    60  	}
    61  
    62  	// 设置响应代码
    63  	if statusCode <= 0 {
    64  		this.writer.WriteHeader(resp.StatusCode)
    65  	} else {
    66  		this.writer.WriteHeader(statusCode)
    67  	}
    68  
    69  	// 输出内容
    70  	var pool = this.bytePool(resp.ContentLength)
    71  	var buf = pool.Get()
    72  	if supportVariables {
    73  		_, err = utils.CopyWithFilter(this.writer, resp.Body, buf.Bytes, func(p []byte) []byte {
    74  			return []byte(this.Format(string(p)))
    75  		})
    76  	} else {
    77  		_, err = io.CopyBuffer(this.writer, resp.Body, buf.Bytes)
    78  	}
    79  	pool.Put(buf)
    80  
    81  	if err != nil {
    82  		if !this.canIgnore(err) {
    83  			remotelogs.Warn("HTTP_REQUEST_URL", "write to client failed: "+err.Error())
    84  		}
    85  	} else {
    86  		this.writer.SetOk()
    87  	}
    88  }