當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。