本文整理汇总了Golang中net/http.Request.Method方法的典型用法代码示例。如果您正苦于以下问题:Golang Request.Method方法的具体用法?Golang Request.Method怎么用?Golang Request.Method使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net/http.Request
的用法示例。
在下文中一共展示了Request.Method方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: wouldMatch
func wouldMatch(router *mux.Router, rq *http.Request, method string) bool {
savedMethod := rq.Method
rq.Method = method
defer func() { rq.Method = savedMethod }()
var matchInfo mux.RouteMatch
return router.Match(rq, &matchInfo)
}
示例2: DownloadPlay
func (this *GoChromeCastHttpServer) DownloadPlay(c web.C, w http.ResponseWriter, r *http.Request) {
if params, err := utils.GetParams(r, "id", "file_path"); err != nil {
w.Header().Set("Content-Type", "application/json")
r := responses.JsonResponse{}
r.Method = "DownloadPlay"
r.Set(nil, err)
io.WriteString(w, utils.RenderResponse(r))
} else {
if sc, display_path, err := this.ds.DownloadPlay(params["id"], params["file_path"]); err != nil {
w.Header().Set("Content-Type", "application/json")
r := responses.JsonResponse{}
r.Method = "DownloadPlay"
r.Set(nil, err)
io.WriteString(w, utils.RenderResponse(r))
} else {
defer func() {
if err == nil {
sc.Close()
}
}()
w.Header().Set("Content-Disposition", "attachment; filename=\""+params["file_path"]+"\"")
http.ServeContent(w, r, display_path, time.Now(), sc)
}
}
}
示例3: 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)
}
示例4: 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)
}
示例5: ServeHTTP
// ServeHTTP servers the actual HTTP request by buidling a context and running
// it through all the handlers.
func (handler *HttpHandler) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) {
// override the method if needed
method := request.Header.Get("X-HTTP-Method-Override")
if method != "" {
request.Method = method
}
// make the context
ctx := webcontext.NewWebContext(responseWriter, request, handler.codecService)
// copy the data
for k, v := range handler.Data {
ctx.Data()[k] = v
}
// run it through the handlers
_, err := handler.Handlers.Handle(ctx)
// do we need to handle an error?
if err != nil {
// set the error
ctx.Data().Set(DataKeyForError, err)
// tell the handler to handle it
handler.ErrorHandler().Handle(ctx)
}
}
示例6: Translate
func Translate(from, to, s string) (t string, err error) {
var url_ = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&format=text&q=" + url.QueryEscape(s) + "&langpair=" + url.QueryEscape(from) + "%7C" + url.QueryEscape(to)
var r *http.Response
if proxy := os.Getenv("HTTP_PROXY"); len(proxy) > 0 {
proxy_url, _ := url.Parse(proxy)
tcp, _ := net.Dial("tcp", proxy_url.Host)
conn := httputil.NewClientConn(tcp, nil)
var req http.Request
req.URL, _ = url.Parse(url_)
req.Method = "GET"
r, err = conn.Do(&req)
} else {
r, err = http.Get(url_)
}
if err == nil {
defer r.Body.Close()
if b, err := ioutil.ReadAll(r.Body); err == nil {
var r interface{}
if err = json.NewDecoder(bytes.NewBuffer(b)).Decode(&r); err == nil {
if r.(map[string]interface{})["responseStatus"].(float64) == 200 {
return r.(map[string]interface{})["responseData"].(map[string]interface{})["translatedText"].(string), nil
} else {
err = errors.New(r.(map[string]interface{})["responseDetails"].(string))
}
}
}
}
return "", err
}
示例7: 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")
}
}
示例8: 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}
}
示例9: post
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)
}
示例10: TestServeFile
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)
}
}
示例11: 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")
}
}
示例12: AllowMethods
func AllowMethods(w http.ResponseWriter, r *http.Request, methods ...string) bool {
r.Method = strings.ToUpper(r.Method)
addHead := false
for _, method := range methods {
if method == r.Method {
return true
}
if method == GET {
if r.Method == HEAD {
return true
}
addHead = true
}
}
allow := strings.Join(methods, ", ")
if addHead {
allow = "HEAD, " + allow
}
w.Header().Set(Allow, allow)
if r.Method == OPTIONS {
w.WriteHeader(http.StatusOK)
return false
}
msg := "requires one of: " + allow
http.Error(w, msg, http.StatusMethodNotAllowed)
return false
}
示例13: 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{}}
}
示例14: 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}
}
示例15: Proxy
func (p *WebsocketProxy) Proxy(w http.ResponseWriter, r *http.Request) {
hj, ok := w.(http.Hijacker)
if !ok {
log.Println("hijack assertion failed", r.Host, r.URL.Path)
p.handler.ServeHTTP(w, r) // last-ditch effort as plain http
return
}
conn, rw, err := hj.Hijack()
if err != nil {
log.Println("hijack failed", r.Host, r.URL.Path, err)
p.handler.ServeHTTP(w, r) // last-ditch effort as plain http
return
}
defer conn.Close()
rw.Flush()
wrapreq := new(http.Request)
wrapreq.Proto = "HTTP/1.1"
wrapreq.ProtoMajor, wrapreq.ProtoMinor = 1, 1
wrapreq.Method = "WEBSOCKET"
wrapreq.Host = r.Host
const dummy = "/"
wrapreq.URL = &url.URL{Path: dummy}
var buf bytes.Buffer
r.Write(&buf)
wrapreq.Body = ioutil.NopCloser(io.MultiReader(&buf, conn))
resp, err := p.transport.RoundTrip(wrapreq)
if err != nil || resp.StatusCode != 200 {
io.WriteString(conn, "HTTP/1.0 503 Gateway Failed\r\n")
io.WriteString(conn, "Connection: close\r\n\r\n")
return
}
defer resp.Body.Close()
io.Copy(conn, resp.Body)
}