Beispiel #1
0
// Put issues a PUT to the specified URL.
// Caller should close r.Body when done reading it.
func authPut(url_, user, pwd, client, clientURL, version, agent, bodyType string,
	body io.Reader) (r *http.Response, err error) {
	var req http.Request
	req.Method = "PUT"
	req.Body = body.(io.ReadCloser)
	if user != "" && pwd != "" {
		req.Header = map[string][]string{
			"Content-Type":           {bodyType},
			"Transfer-Encoding":      {"chunked"},
			"User-Agent":             {agent},
			"X-Fluidinfo-Client":     {client},
			"X-Fluidinfo-Client-URL": {clientURL},
			"X-Fluidinfo-Version":    {version},
			"Authorization":          {"Basic " + encodedUsernameAndPassword(user, pwd)},
		}
	} else {
		req.Header = map[string][]string{
			"Content-Type":           {bodyType},
			"Transfer-Encoding":      {"chunked"},
			"User-Agent":             {agent},
			"X-Fluidinfo-Client":     {client},
			"X-Fluidinfo-Client-URL": {clientURL},
			"X-Fluidinfo-Version":    {version},
		}
	}

	req.URL, err = url.Parse(url_)
	if err != nil {
		return nil, err
	}

	return send(&req)
}
Beispiel #2
0
func main() {
	if 3 <= len(os.Args) && len(os.Args) <= 5 {
		method := os.Args[1]
		ackordurl, _ := url.Parse(os.Args[2])

		request := new(http.Request)

		if len(os.Args) == 3 && method == "GET" {
		} else if len(os.Args) == 3 && method == "DELETE" {
		} else if len(os.Args) == 4 && method == "PUT" {
			request.Header = make(http.Header)
			request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
			myBody := bytes.NewBufferString(fmt.Sprintf("value=%s", os.Args[3]))
			request.Body = ioutil.NopCloser(myBody)
			request.ContentLength = int64(myBody.Len())
		} else if len(os.Args) == 5 && method == "POST" {
			request.Header = make(http.Header)
			request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
			myBody := bytes.NewBufferString(fmt.Sprintf("key=%s&value=%s", os.Args[3], os.Args[4]))
			request.Body = ioutil.NopCloser(myBody)
			request.ContentLength = int64(myBody.Len())
		} else {
			fmt.Println("wrong method")
			return
		}

		client := new(http.Client)
		request.Method = method
		request.URL = ackordurl

		bb, _ := httputil.DumpRequest(request, true)
		fmt.Println("Request: " + string(bb[:]))

		response, err := client.Do(request)
		if err != nil {
			fmt.Println(err.Error())
			return
		}

		rb, _ := httputil.DumpResponse(response, true)
		fmt.Println("Response body: " + string(rb[:]))

	} else {
		fmt.Println("rester POST http://localhost:12080/storage/ MyText \"Some text here.\"")
		fmt.Println("rester GET http://localhost:12080/storage/MyText")
		fmt.Println("rester PUT http://localhost:12080/storage/MyText \"Some other text.\"")
		fmt.Println("rester DELETE http://localhost:12080/storage/MyText")
	}
}
func getCodes() {
	//并发写文件必须要有锁啊,怎么还是串行程序的思维啊。
	fileName := "./data/data.html"

	f, err := os.Create(fileName) //其实这里的 O_RDWR应该是 O_RDWR|O_CREATE,也就是文件不存在的情况下就建一个空文件,但是因为windows下还有BUG,如果使用这个O_CREATE,就会直接清空文件,所以这里就不用了这个标志,你自己事先建立好文件。
	if err != nil {
		panic(err)
	}

	defer f.Close()

	urls := "http://quote.eastmoney.com/stocklist.html"
	var req http.Request
	req.Method = "GET"
	req.Close = true
	req.URL, err = url.Parse(urls)
	if err != nil {
		panic(err)
	}

	header := http.Header{}
	header.Set("User-Agent", UA)
	req.Header = header
	resp, err := http.DefaultClient.Do(&req)
	if err == nil {
		if resp.StatusCode == 200 {
			io.Copy(f, resp.Body)
		} else {
			fmt.Println("http get StatusCode")
		}
		defer resp.Body.Close()
	} else {
		fmt.Println("http get error")
	}
}
func (connection *CloudControllerConnection) createHTTPRequest(passedRequest Request) (*http.Request, error) {
	var request *http.Request
	var err error
	if passedRequest.URI != "" {
		request, err = http.NewRequest(
			passedRequest.Method,
			fmt.Sprintf("%s%s", connection.URL, passedRequest.URI),
			&bytes.Buffer{},
		)
	} else {
		request, err = connection.requestGenerator.CreateRequest(
			passedRequest.RequestName,
			passedRequest.Params,
			&bytes.Buffer{},
		)
		if err == nil {
			request.URL.RawQuery = passedRequest.Query.Encode()
		}
	}
	if err != nil {
		return nil, err
	}

	if passedRequest.Header != nil {
		request.Header = passedRequest.Header
	}

	request.Header.Set("accept", "application/json")
	request.Header.Set("content-type", "application/json")

	// request.Header.Set("Connection", "close")
	// request.Header.Set("User-Agent", "go-cli "+cf.Version+" / "+runtime.GOOS)

	return request, nil
}
Beispiel #5
0
// RoundTrip makes a request expecting a 401 response that will require digest
// authentication.  It creates the credentials it needs and makes a follow-up
// request.
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
	if t.Transport == nil {
		return nil, ErrNilTransport
	}

	// Copy the request so we don't modify the input.
	req2 := new(http.Request)
	*req2 = *req
	req2.Header = make(http.Header)
	for k, s := range req.Header {
		req2.Header[k] = s
	}

	// Make a request to get the 401 that contains the challenge.
	resp, err := t.Transport.RoundTrip(req)
	if err != nil || resp.StatusCode != 401 {
		return resp, err
	}
	chal := resp.Header.Get("WWW-Authenticate")
	c, err := parseChallenge(chal)
	if err != nil {
		return resp, err
	}

	// Form credentials based on the challenge.
	cr := t.newCredentials(req2, c)
	auth, err := cr.authorize()
	if err != nil {
		return resp, err
	}

	// Make authenticated request.
	req2.Header.Set("Authorization", auth)
	return t.Transport.RoundTrip(req2)
}
Beispiel #6
0
// Head returns *BeegoHttpRequest with HEAD method.
func Head(url string) *BeegoHttpRequest {
	var req http.Request
	req.Method = "HEAD"
	req.Header = http.Header{}
	req.Header.Set("User-Agent", defaultUserAgent)
	return &BeegoHttpRequest{url, &req, map[string]string{}, false, 60 * time.Second, 60 * time.Second, nil, nil, nil}
}
Beispiel #7
0
func handleFilteredHTTP(w http.ResponseWriter, r *http.Request) {
	// Patch up RemoteAddr so it looks reasonable.
	if addr := r.Header.Get("X-Appengine-Internal-Remote-Addr"); addr != "" {
		r.RemoteAddr = addr
	} else {
		// Should not normally reach here, but pick
		// a sensible default anyway.
		r.RemoteAddr = "127.0.0.1"
	}

	// Create a private copy of the Request that includes headers that are
	// private to the runtime and strip those headers from the request that the
	// user application sees.
	creq := *r
	r.Header = make(http.Header)
	for name, values := range creq.Header {
		if !strings.HasPrefix(name, "X-Appengine-Internal-") {
			r.Header[name] = values
		}
	}
	ctxsMu.Lock()
	ctxs[r] = &context{req: &creq}
	ctxsMu.Unlock()

	http.DefaultServeMux.ServeHTTP(w, r)

	ctxsMu.Lock()
	delete(ctxs, r)
	ctxsMu.Unlock()
}
func TestWrongVersion(t *testing.T) {
	// wring version string, expect a 404

	handler := NewStaticHandler(
		http.Dir("."),
		"1234567",
		nil,
		true,
	)

	urlObj, err := url.Parse("http://1.2.3.4/wrong_version/handler.go")
	if err != nil {
		t.Fatal(err)
	}
	r := http.Request{
		Method: "GET",
		URL:    urlObj,
	}
	r.Header = http.Header{}

	recorder := httptest.NewRecorder()

	handler.ServeHTTP(recorder, &r)

	codeIs(t, recorder, 404)
}
Beispiel #9
0
func download(dictId string, dictNum string, downUrl string) {
	fileName := SAVEPATH + dictId + "-" + dictNum + ".scel"
	f, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, 0666) //其实这里的 O_RDWR应该是 O_RDWR|O_CREATE,也就是文件不存在的情况下就建一个空文件,但是因为windows下还有BUG,如果使用这个O_CREATE,就会直接清空文件,所以这里就不用了这个标志,你自己事先建立好文件。
	if err != nil {
		panic(err)
	}

	defer f.Close()

	var req http.Request
	req.Method = "GET"
	req.Close = true
	req.URL, _ = url.Parse(downUrl)

	header := http.Header{}
	header.Set("User-Agent", UA)
	header.Set("Host", HOST)
	header.Set("Referer", REFERER+dictId)
	req.Header = header
	resp, err := http.DefaultClient.Do(&req)
	if err == nil {
		if resp.StatusCode == 200 {
			fmt.Println(dictId + ":sucess")
			_, err = io.Copy(f, resp.Body)
			if err != nil {
				panic(err)
			}
		} else {
			fmt.Println(dictId + ":" + strconv.Itoa(resp.StatusCode))
		}
		defer resp.Body.Close()
	} else {
		fmt.Println(dictId + ":error")
	}
}
Beispiel #10
0
func Delete(url string) *HttpRequestBuilder {
	var req http.Request
	req.Method = "DELETE"
	req.Header = http.Header{}
	req.Header.Set("User-Agent", defaultUserAgent)
	return &HttpRequestBuilder{url, &req, nil, map[string]string{}}
}
func TestHTTPHeaderFilters(t *testing.T) {
	filters := HTTPHeaderFilters{}

	err := filters.Set("Header1:^$")
	if err != nil {
		t.Error("Should not error on Header1:^$")
	}

	err = filters.Set("Header2:^:$")
	if err != nil {
		t.Error("Should not error on Header2:^:$")
	}

	err = filters.Set("Header3-^$")
	if err == nil {
		t.Error("Should error on Header2:^:$")
	}

	req := http.Request{}
	req.Header = make(map[string][]string)
	req.Header.Add("Header1", "")
	req.Header.Add("Header2", ":")
	req.Header.Add("Header3", "Irrelevant")

	if !filters.Good(&req) {
		t.Error("Request should pass filters")
	}
}
Beispiel #12
0
// Put returns *BeegoHttpRequest with PUT method.
func Put(url string) *BeegoHttpRequest {
	var req http.Request
	var resp http.Response
	req.Method = "PUT"
	req.Header = http.Header{}
	return &BeegoHttpRequest{url, &req, map[string]string{}, map[string]string{}, defaultSetting, &resp, nil}
}
Beispiel #13
0
func main() {
	f, err := os.OpenFile("./file.exe", os.O_RDWR, 0666) //其实这里的 O_RDWR应该是 O_RDWR|O_CREATE,也就是文件不存在的情况下就建一个空文件,但是因为windows下还有BUG,如果使用这个O_CREATE,就会直接清空文件,所以这里就不用了这个标志,你自己事先建立好文件。
	if err != nil {
		panic(err)
	}
	stat, err := f.Stat() //获取文件状态
	if err != nil {
		panic(err)
	}
	f.Seek(stat.Size(), 0) //把文件指针指到文件末,当然你说为何不直接用 O_APPEND 模式打开,没错是可以。我这里只是试验。
	url := "http://dl.google.com/chrome/install/696.57/chrome_installer.exe"
	var req http.Request
	req.Method = "GET"
	//req.UserAgent = UA
	req.Close = true
	req.URL, err = http.ParseURL(url)
	if err != nil {
		panic(err)
	}
	header := http.Header{}
	header.Set("Range", "bytes="+strconv.Itoa64(stat.Size)+"-")
	req.Header = header
	resp, err := http.DefaultClient.Do(&req)
	if err != nil {
		panic(err)
	}
	written, err := io.Copy(f, resp.Body)
	if err != nil {
		panic(err)
	}
	println("written: ", written)
}
func (connection *CloudControllerConnection) createHTTPRequest(passedRequest Request) (*http.Request, error) {
	var request *http.Request
	var err error
	if passedRequest.URI != "" {
		request, err = http.NewRequest(
			passedRequest.Method,
			fmt.Sprintf("%s%s", connection.URL, passedRequest.URI),
			&bytes.Buffer{},
		)
	} else {
		request, err = connection.requestGenerator.CreateRequest(
			passedRequest.RequestName,
			passedRequest.URIParams,
			&bytes.Buffer{},
		)
		if err == nil {
			request.URL.RawQuery = passedRequest.Query.Encode()
		}
	}
	if err != nil {
		return nil, err
	}

	if passedRequest.Header != nil {
		request.Header = passedRequest.Header
	}

	return request, nil
}
Beispiel #15
0
func (l *HttpLocation) copyRequest(req *http.Request, body netutils.MultiReader, endpoint endpoint.Endpoint) *http.Request {
	outReq := new(http.Request)
	*outReq = *req // includes shallow copies of maps, but we handle this below

	// Set the body to the enhanced body that can be re-read multiple times and buffered to disk
	outReq.Body = body

	endpointURL := endpoint.GetUrl()
	outReq.URL.Scheme = endpointURL.Scheme
	outReq.URL.Host = endpointURL.Host
	outReq.URL.Opaque = req.RequestURI
	// raw query is already included in RequestURI, so ignore it to avoid dupes
	outReq.URL.RawQuery = ""

	outReq.Proto = "HTTP/1.1"
	outReq.ProtoMajor = 1
	outReq.ProtoMinor = 1

	// Overwrite close flag so we can keep persistent connection for the backend servers
	outReq.Close = false

	outReq.Header = make(http.Header)
	netutils.CopyHeaders(outReq.Header, req.Header)
	return outReq
}
Beispiel #16
0
// createUpstremRequest shallow-copies r into a new request
// that can be sent upstream.
func createUpstreamRequest(r *http.Request) *http.Request {
	outreq := new(http.Request)
	*outreq = *r // includes shallow copies of maps, but okay

	// Restore URL Path if it has been modified
	if outreq.URL.RawPath != "" {
		outreq.URL.Opaque = outreq.URL.RawPath
	}

	// Remove hop-by-hop headers to the backend. Especially
	// important is "Connection" because we want a persistent
	// connection, regardless of what the client sent to us. This
	// is modifying the same underlying map from r (shallow
	// copied above) so we only copy it if necessary.
	for _, h := range hopHeaders {
		if outreq.Header.Get(h) != "" {
			outreq.Header = make(http.Header)
			copyHeader(outreq.Header, r.Header)
			outreq.Header.Del(h)
		}
	}

	if clientIP, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
		// If we aren't the first proxy, retain prior
		// X-Forwarded-For information as a comma+space
		// separated list and fold multiple headers into one.
		if prior, ok := outreq.Header["X-Forwarded-For"]; ok {
			clientIP = strings.Join(prior, ", ") + ", " + clientIP
		}
		outreq.Header.Set("X-Forwarded-For", clientIP)
	}

	return outreq
}
Beispiel #17
0
// NewFastHTTPHandler wraps net/http handler to fasthttp request handler,
// so it can be passed to fasthttp server.
//
// While this function may be used for easy switching from net/http to fasthttp,
// it has the following drawbacks comparing to using manually written fasthttp
// request handler:
//
//     * A lot of useful functionality provided by fasthttp is missing
//       from net/http handler.
//     * net/http -> fasthttp handler conversion has some overhead,
//       so the returned handler will be always slower than manually written
//       fasthttp handler.
//
// So it is advisable using this function only for quick net/http -> fasthttp
// switching. Then manually convert net/http handlers to fasthttp handlers
// according to https://github.com/valyala/fasthttp#switching-from-nethttp-to-fasthttp .
func NewFastHTTPHandler(h http.Handler) fasthttp.RequestHandler {
	return func(ctx *fasthttp.RequestCtx) {
		var r http.Request

		body := ctx.PostBody()
		r.Method = string(ctx.Method())
		r.Proto = "HTTP/1.1"
		r.ProtoMajor = 1
		r.ProtoMinor = 1
		r.RequestURI = string(ctx.RequestURI())
		r.ContentLength = int64(len(body))
		r.Host = string(ctx.Host())
		r.RemoteAddr = ctx.RemoteAddr().String()

		hdr := make(http.Header)
		ctx.Request.Header.VisitAll(func(k, v []byte) {
			hdr.Set(string(k), string(v))
		})
		r.Header = hdr
		r.Body = &netHTTPBody{body}

		var w netHTTPResponseWriter
		h.ServeHTTP(&w, &r)

		ctx.SetStatusCode(w.StatusCode())
		for k, vv := range w.Header() {
			for _, v := range vv {
				ctx.Response.Header.Set(k, v)
			}
		}
		ctx.Write(w.body)
	}
}
Beispiel #18
0
// Do performs a Parse API call. This method modifies the request and adds the
// Authentication headers. The body is JSON encoded and for responses in the
// 2xx or 3xx range the response will be JSON decoded into result, for others
// an error of type Error will be returned.
func (c *Client) Do(req *http.Request, body, result interface{}) (*http.Response, error) {
	// we need to buffer as Parse requires a Content-Length
	if body != nil {
		bd, err := json.Marshal(body)
		if err != nil {
			return nil, err
		}
		if req.Header == nil {
			req.Header = make(http.Header)
		}
		req.Header.Set("Content-Type", "application/json")
		req.Body = ioutil.NopCloser(bytes.NewReader(bd))
		req.ContentLength = int64(len(bd))
	}

	res, err := c.RoundTrip(req)
	if err != nil {
		return res, err
	}
	defer res.Body.Close()

	if result != nil {
		if err := json.NewDecoder(res.Body).Decode(result); err != nil {
			return res, err
		}
	}
	return res, nil
}
func TestSecondRequest(t *testing.T) {
	// sent with If-Modified-Since, expect a 304

	handler := NewStaticHandler(
		http.Dir("."),
		"1234567",
		nil,
		false,
	)

	handler = handler.(*staticHandler)

	urlObj, err := url.Parse("http://1.2.3.4/1234567/handler.go")
	if err != nil {
		t.Fatal(err)
	}
	r := http.Request{
		Method: "GET",
		URL:    urlObj,
	}
	r.Header = http.Header{}
	r.Header.Set("If-Modified-Since", "Sat, 01 Apr 2113 04:15:01 GMT")

	recorder := httptest.NewRecorder()

	handler.ServeHTTP(recorder, &r)

	codeIs(t, recorder, 304)
}
Beispiel #20
0
// Updates the Money Header values for a *http.Request
func UpdateMNYHeaderReq(req *http.Request, allMNY []*Money) *http.Request {
	header := DelAllMNYHeaders(req.Header)
	header = AddAllMNYHeaders(header, allMNY)
	req.Header = header

	return req
}
func TestDevelopement(t *testing.T) {
	// right version string, expect a 200

	handler := NewStaticHandler(
		http.Dir("."),
		"1234567",
		nil,
		true,
	)

	urlObj, err := url.Parse("http://1.2.3.4/1234567/handler.go")
	if err != nil {
		t.Fatal(err)
	}
	r := http.Request{
		Method: "GET",
		URL:    urlObj,
	}
	r.Header = http.Header{}

	recorder := httptest.NewRecorder()

	handler.ServeHTTP(recorder, &r)

	codeIs(t, recorder, 200)
}
Beispiel #22
0
Datei: fwd.go Projekt: narma/oxy
func (f *Forwarder) copyRequest(req *http.Request, u *url.URL) *http.Request {
	outReq := new(http.Request)
	*outReq = *req // includes shallow copies of maps, but we handle this below

	outReq.URL = utils.CopyURL(req.URL)
	outReq.URL.Scheme = u.Scheme
	outReq.URL.Host = u.Host
	// workaround for https://github.com/golang/go/issues/10433
	outReq.URL.Opaque = mergeStartingSlashes(req.RequestURI)
	// raw query is already included in RequestURI, so ignore it to avoid dupes
	outReq.URL.RawQuery = ""
	// Do not pass client Host header unless optsetter PassHostHeader is set.
	if f.passHost != true {
		outReq.Host = u.Host
	}
	outReq.Proto = "HTTP/1.1"
	outReq.ProtoMajor = 1
	outReq.ProtoMinor = 1

	// Overwrite close flag so we can keep persistent connection for the backend servers
	outReq.Close = false

	outReq.Header = make(http.Header)
	utils.CopyHeaders(outReq.Header, req.Header)

	if f.rewriter != nil {
		f.rewriter.Rewrite(outReq)
	}
	return outReq
}
Beispiel #23
0
Datei: fwd.go Projekt: pasdoy/oxy
func (f *Forwarder) copyRequest(req *http.Request, u *url.URL) *http.Request {
	outReq := new(http.Request)
	*outReq = *req // includes shallow copies of maps, but we handle this below

	outReq.URL = utils.CopyURL(req.URL)
	outReq.URL.Scheme = u.Scheme
	outReq.URL.Host = u.Host
	outReq.URL.Opaque = req.RequestURI
	// raw query is already included in RequestURI, so ignore it to avoid dupes
	outReq.URL.RawQuery = ""
	// Go doesn't implicitly pass the host header unless you set Host on the request
	outReq.Host = u.Host

	outReq.Proto = "HTTP/1.1"
	outReq.ProtoMajor = 1
	outReq.ProtoMinor = 1

	// Overwrite close flag so we can keep persistent connection for the backend servers
	outReq.Close = false

	outReq.Header = make(http.Header)
	utils.CopyHeaders(outReq.Header, req.Header)

	if f.rewriter != nil {
		f.rewriter.Rewrite(outReq)
	}
	return outReq
}
Beispiel #24
0
// This function alters the original request - adds/removes headers, removes hop headers,
// changes the request path.
func rewriteRequest(req *http.Request, cmd *command.Forward, upstream *command.Upstream) *http.Request {
	outReq := new(http.Request)
	*outReq = *req // includes shallow copies of maps, but we handle this below

	outReq.URL.Scheme = upstream.Scheme
	outReq.URL.Host = fmt.Sprintf("%s:%d", upstream.Host, upstream.Port)
	if len(cmd.RewritePath) != 0 {
		outReq.URL.Path = cmd.RewritePath
	}

	outReq.URL.RawQuery = req.URL.RawQuery

	outReq.Proto = "HTTP/1.1"
	outReq.ProtoMajor = 1
	outReq.ProtoMinor = 1
	outReq.Close = false

	glog.Infof("Proxying request to: %v", outReq)

	outReq.Header = make(http.Header)
	netutils.CopyHeaders(outReq.Header, req.Header)

	if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
		// TODO(pquerna): configure this?  Not all backends properly parse the header..
		if TRUST_FORWARD_HEADER {
			if prior, ok := outReq.Header["X-Forwarded-For"]; ok {
				clientIP = strings.Join(prior, ", ") + ", " + clientIP
			}
		}
		outReq.Header.Set("X-Forwarded-For", clientIP)
	}

	if req.TLS != nil {
		outReq.Header.Set("X-Forwarded-Proto", "https")
	} else {
		outReq.Header.Set("X-Forwarded-Proto", "http")
	}

	if req.Host != "" {
		outReq.Header.Set("X-Forwarded-Host", req.Host)
	}

	outReq.Header.Set("X-Forwarded-Server", vulcanHostname)

	if len(cmd.RemoveHeaders) != 0 {
		netutils.RemoveHeaders(cmd.RemoveHeaders, outReq.Header)
	}

	// Add generic instructions headers to the request
	if len(cmd.AddHeaders) != 0 {
		glog.Info("Proxying instructions headers:", cmd.AddHeaders)
		netutils.CopyHeaders(outReq.Header, cmd.AddHeaders)
	}

	// Remove hop-by-hop headers to the backend.  Especially
	// important is "Connection" because we want a persistent
	// connection, regardless of what the client sent to us.
	netutils.RemoveHeaders(hopHeaders, outReq.Header)
	return outReq
}
Beispiel #25
0
// copyRequest creates a new proxy request with some modifications from an original request.
func copyRequest(originalRequest *http.Request) *http.Request {
	pr := new(http.Request)
	*pr = *originalRequest
	pr.Proto = "HTTP/1.1"
	pr.ProtoMajor = 1
	pr.ProtoMinor = 1
	pr.Close = false
	pr.Header = make(http.Header)
	pr.URL.Scheme = "http"
	pr.URL.Path = originalRequest.URL.Path

	// Copy all header fields.
	for key, values := range originalRequest.Header {
		for _, value := range values {
			pr.Header.Add(key, value)
		}
	}

	// Remove ignored header fields.
	for _, header := range ignoredHeaderNames {
		pr.Header.Del(header)
	}

	// Append this machine's host name into X-Forwarded-For.
	if requestHost, _, err := net.SplitHostPort(originalRequest.RemoteAddr); err == nil {
		if originalValues, ok := pr.Header["X-Forwarded-For"]; ok {
			requestHost = strings.Join(originalValues, ", ") + ", " + requestHost
		}
		pr.Header.Set("X-Forwarded-For", requestHost)
	}

	return pr
}
Beispiel #26
0
func post(url_ string, oauthHeaders map[string]string) (r *http.Response, err error) {
	var req http.Request
	req.Method = "POST"
	req.ProtoMajor = 1
	req.ProtoMinor = 1
	req.Close = true
	req.Header = map[string][]string{
		"Authorization": {"OAuth "},
	}
	req.TransferEncoding = []string{"chunked"}

	first := true
	for k, v := range oauthHeaders {
		if first {
			first = false
		} else {
			req.Header["Authorization"][0] += ",\n    "
		}
		req.Header["Authorization"][0] += k + "=\"" + v + "\""
	}

	req.URL, err = url.Parse(url_)
	if err != nil {
		return nil, err
	}

	return send(&req)
}
Beispiel #27
0
func (proxy *Proxy) copyRequest(r *http.Request) *http.Request {
	proxyRequest := new(http.Request)
	*proxyRequest = *r
	proxyRequest.Proto = "HTTP/1.1"
	proxyRequest.ProtoMajor = 1
	proxyRequest.ProtoMinor = 1
	proxyRequest.Close = false
	proxyRequest.Header = make(http.Header)
	proxyRequest.URL.Scheme = "http"
	proxyRequest.URL.Path = r.URL.Path

	for key, values := range r.Header {
		for _, value := range values {
			proxyRequest.Header.Add(key, value)
		}
	}
	for _, headerName := range ignoredHeaderNames {
		proxyRequest.Header.Del(headerName)
	}
	if requestHost, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
		if values, ok := proxyRequest.Header["X-Forwarded-For"]; ok {
			requestHost = strings.Join(values, ", ") + ", " + requestHost
		}
		proxyRequest.Header.Set("X-Forwarded-For", requestHost)
	}

	return proxyRequest
}
Beispiel #28
0
func createRequestToken(tokenUrl, consumerKey, consumerSecret string) (*requestToken, error) {
	requestTokenUrl, _ := url.Parse(tokenUrl)
	req := http.Request{
		URL:        requestTokenUrl,
		Method:     "POST",
		ProtoMajor: 1,
		ProtoMinor: 1,
		Close:      true,
	}
	req.Header = http.Header{}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	signRequest(&req, consumerKey, consumerSecret)

	resp, err := http.DefaultClient.Do(&req)
	if err != nil {
		panic(err)
	}

	requestToken, err := parserequestToken(resp.Body)
	if err != nil {
		return nil, err
	}
	return requestToken, nil
}
Beispiel #29
0
func TestServeFile(t *testing.T) {
	defer afterTest(t)
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ServeFile(w, r, "testdata/file")
	}))
	defer ts.Close()

	var err error

	file, err := ioutil.ReadFile(testFile)
	if err != nil {
		t.Fatal("reading file:", err)
	}

	// set up the Request (re-used for all tests)
	var req http.Request
	req.Header = make(http.Header)
	if req.URL, err = url.Parse(ts.URL); err != nil {
		t.Fatal("ParseURL:", err)
	}
	req.Method = "GET"

	// straight GET
	_, body := getBody(t, "straight get", req)
	if !bytes.Equal(body, file) {
		t.Fatalf("body mismatch: got %q, want %q", body, file)
	}
}
Beispiel #30
0
func TestGetMime(t *testing.T) {
	m1 := &FakeMarshaller{"fake/mime1"}
	m2 := &FakeMarshaller{"fake/mime2"}
	m3 := &FakeMarshaller{"fake/mime3"}
	type Test struct {
		marshallers []Marshaller
		header      http.Header
		field       string
		fallback    Marshaller
		target      Marshaller
	}
	var tests = []Test{
		{[]Marshaller{m1, m2, m3}, http.Header{"Content-Type": []string{"fake/mime1"}}, "Content-Type", m2, m1},
		{[]Marshaller{m1, m2, m3}, http.Header{"Content-Type": []string{"fake/nonexist"}}, "Content-Type", m2, m2},
		{[]Marshaller{m1, m2, m3}, http.Header{"Content-Type": []string{"fake/nonexist"}}, "Content-Type", nil, nil},
	}
	for i, test := range tests {
		req := new(http.Request)
		req.Header = test.header
		ctx := &Context{
			Request: req,
		}
		p := NewMimeParser(test.marshallers...)
		m := p.getMime(ctx, test.field, test.fallback)
		assert.Equal(t, m, test.target, "test %d", i)
	}
}