当前位置: 首页>>代码示例>>Golang>>正文


Golang Request.Header方法代码示例

本文整理汇总了Golang中net/http.Request.Header方法的典型用法代码示例。如果您正苦于以下问题:Golang Request.Header方法的具体用法?Golang Request.Header怎么用?Golang Request.Header使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在net/http.Request的用法示例。


在下文中一共展示了Request.Header方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: authPut

// 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)
}
开发者ID:micrypt,项目名称:gofluidinfo,代码行数:35,代码来源:fluidinfo.go

示例2: main

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")
	}
}
开发者ID:davnym-4,项目名称:ackord,代码行数:49,代码来源:rester.go

示例3: getCodes

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")
	}
}
开发者ID:freedream520,项目名称:gettrackersdata,代码行数:35,代码来源:getcode.go

示例4: createHTTPRequest

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
}
开发者ID:fujitsu-cf,项目名称:cli,代码行数:35,代码来源:cloud_controller_connection.go

示例5: RoundTrip

// 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)
}
开发者ID:iPowow,项目名称:lbManager,代码行数:38,代码来源:digest.go

示例6: Head

// 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}
}
开发者ID:JustStone,项目名称:gogs,代码行数:8,代码来源:httplib.go

示例7: handleFilteredHTTP

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()
}
开发者ID:LeXa4894,项目名称:test,代码行数:30,代码来源:api_dev.go

示例8: TestWrongVersion

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)
}
开发者ID:hasantayyar,项目名称:go-static-forever,代码行数:26,代码来源:handler_test.go

示例9: download

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")
	}
}
开发者ID:jinguanio,项目名称:sogou_dict,代码行数:35,代码来源:download.go

示例10: Delete

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{}}
}
开发者ID:rrlrrlouw,项目名称:tweetdumper,代码行数:7,代码来源:httplib.go

示例11: TestHTTPHeaderFilters

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")
	}
}
开发者ID:WIZARD-CXY,项目名称:golang-devops-stuff,代码行数:28,代码来源:settings_header_filters_test.go

示例12: Put

// 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}
}
开发者ID:kalbasit,项目名称:beego,代码行数:8,代码来源:httplib.go

示例13: main

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)
}
开发者ID:bonly,项目名称:exercise,代码行数:32,代码来源:20110905_download.go

示例14: createHTTPRequest

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
}
开发者ID:sebrandon1,项目名称:cli,代码行数:29,代码来源:cloud_controller_connection.go

示例15: copyRequest

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
}
开发者ID:irasmaster,项目名称:vulcan,代码行数:25,代码来源:httploc.go


注:本文中的net/http.Request.Header方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。