Beispiel #1
0
func httpProxy(writer http.ResponseWriter, request *http.Request) {

	proxyRequest := new(http.Request)
	*proxyRequest = *request

	log.Printf("request = %s %s", request.Method, request.URL.Host)

	if strings.ToUpper(proxyRequest.Method) == "CONNECT" {
		hostPort := request.URL.Host
		pandora, err := dialer.Dial("tcp", hostPort) // tuner.pandora.com:443
		if err != nil {
			log.Printf("pianobarproxy: error: %v", err)
			writer.WriteHeader(http.StatusInternalServerError)
			return
		}

		client, writer, err := writer.(http.Hijacker).Hijack()
		writer.WriteString("HTTP/1.0 200 Connection Established\r\n\r\n")
		writer.Flush()
		go pipe(client, pandora)
		go pipe(pandora, client)
		return
	}
	proxyRequest.Proto = "HTTP/1.1"
	proxyRequest.ProtoMajor = 1
	proxyRequest.ProtoMinor = 1
	proxyRequest.Close = false

	// Remove the connection header to the backend.  We want a
	// persistent connection, regardless of what the client sent
	// to us.
	if proxyRequest.Header.Get("Connection") != "" {
		proxyRequest.Header = make(http.Header)
		copyHeader(proxyRequest.Header, request.Header)
		proxyRequest.Header.Del("Connection")
	}

	response, err := transport.RoundTrip(proxyRequest)
	if err != nil {
		log.Printf("pianobarproxy: error: %v", err)
		writer.WriteHeader(http.StatusInternalServerError)
		return
	}

	copyHeader(writer.Header(), response.Header)

	writer.WriteHeader(response.StatusCode)

	if response.Body != nil {
		io.Copy(io.Writer(writer), response.Body)
	}
}