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


Golang http.Request类代码示例

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


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

示例1: Validate

func (s *sessionData) Validate(r *http.Request) (validSessionID bool, validXSRFToken bool, err error) {
	validSessionID = false
	validXSRFToken = false

	sessionID, err := r.Cookie("Interlock-Token")

	if err != nil {
		return
	}

	XSRFToken := r.Header.Get("X-XSRFToken")

	session.Lock()
	defer session.Unlock()

	if session.SessionID == sessionID.Value {
		validSessionID = true
	} else {
		err = errors.New("invalid session")
	}

	if session.XSRFToken == XSRFToken {
		validXSRFToken = true
	} else {
		err = errors.New("missing XSRFToken")
	}

	return
}
开发者ID:nightdomain,项目名称:interlock,代码行数:29,代码来源:session.go

示例2: dropSeries

func (api *API) dropSeries(r *http.Request) (interface{}, *apiError) {
	r.ParseForm()
	if len(r.Form["match[]"]) == 0 {
		return nil, &apiError{errorBadData, fmt.Errorf("no match[] parameter provided")}
	}
	fps := map[model.Fingerprint]struct{}{}

	for _, lm := range r.Form["match[]"] {
		matchers, err := promql.ParseMetricSelector(lm)
		if err != nil {
			return nil, &apiError{errorBadData, err}
		}
		for fp := range api.Storage.MetricsForLabelMatchers(matchers...) {
			fps[fp] = struct{}{}
		}
	}
	for fp := range fps {
		api.Storage.DropMetricsForFingerprints(fp)
	}

	res := struct {
		NumDeleted int `json:"numDeleted"`
	}{
		NumDeleted: len(fps),
	}
	return res, nil
}
开发者ID:brutus333,项目名称:prometheus,代码行数:27,代码来源:api.go

示例3: send

func (s *loggingSender) send(ctx context.Context, r *http.Request, message string) {
	payload := map[string]interface{}{
		"eventTime":      time.Now().In(time.UTC).Format(time.RFC3339Nano),
		"message":        message,
		"serviceContext": s.serviceContext,
	}
	if r != nil {
		payload["context"] = map[string]interface{}{
			"httpRequest": map[string]interface{}{
				"method":    r.Method,
				"url":       r.Host + r.RequestURI,
				"userAgent": r.UserAgent(),
				"referrer":  r.Referer(),
				"remoteIp":  r.RemoteAddr,
			},
		}
	}
	e := logging.Entry{
		Severity: logging.Error,
		Payload:  payload,
	}
	err := s.logger.LogSync(ctx, e)
	if err != nil {
		log.Println("Error writing error report:", err, "report:", payload)
	}
}
开发者ID:trythings,项目名称:trythings,代码行数:26,代码来源:errors.go

示例4: readRequest

// Read next request from connection.
func (c *conn) readRequest() (r *request, w *response, err error) {
	if c.hijacked {
		return nil, nil, ErrHijacked
	}
	c.lr.N = int64(c.server.maxHeaderBytes()) + 4096 /* bufio slop */
	var req *http.Request
	if req, err = http.ReadRequest(c.buf.Reader); err != nil {
		if c.lr.N == 0 {
			return nil, nil, errTooLarge
		}
		return nil, nil, err
	}
	c.lr.N = noLimit

	req.RemoteAddr = c.remoteAddr

	w = new(response)
	w.conn = c

	r = new(request)
	r.Request = req
	r.w = w

	w.reqWantsHttp10KeepAlive = r.wantsHttp10KeepAlive()
	w.reqMethod = r.Method
	w.reqProtoAtLeast10 = r.ProtoAtLeast(1, 0)
	w.reqProtoAtLeast11 = r.ProtoAtLeast(1, 1)
	w.reqExpectsContinue = r.expectsContinue()
	w.reqContentLength = r.ContentLength

	w.header = make(http.Header)
	w.contentLength = -1
	return r, w, nil
}
开发者ID:ndzj081221130,项目名称:router-src,代码行数:35,代码来源:server.go

示例5: handler

// handler echos the Path component of the requested URL.
func handler(w http.ResponseWriter, r *http.Request) {
	mu.Lock()
	count++
	mu.Unlock()
	fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
	fmt.Fprintf(w, "%s %s %s\n", r.Method, r.URL, r.Proto)
	for k, v := range r.Header {
		fmt.Fprintf(w, "Header[%q] = %q\n", k, v)
	}
	fmt.Fprintf(w, "Host = %q\n", r.Host)
	fmt.Fprintf(w, "RemoteAddr = %q\n", r.RemoteAddr)
	if err := r.ParseForm(); err != nil {
		log.Print(err)
	}
	for k, v := range r.Form {
		fmt.Fprintf(w, "Form[%q] = %q\n", k, v)
		// http://localhost:8000/?cycles=20
		if k == "cycles" {
			cycles := strings.Join(v, "")
			ncycles, _ := strconv.Atoi(cycles)
			count = count + ncycles
			switch coinflip() {
			case "heads":
				count++
			case "tails":
				count--
			default:
				fmt.Fprintf(w, "yo dawg %d\n", count)
			}
		}
	}
}
开发者ID:walrus7521,项目名称:code,代码行数:33,代码来源:server.go

示例6: DeleteMessageHandler

func (s *Server) DeleteMessageHandler(w http.ResponseWriter, r *http.Request) {
	login, err := getYandexLogin(r)
	if login == "" || err != nil {
		writeError(w, 403, "forbidden")
		return
	}

	subject := r.FormValue("subject")
	if subject != "" {
		log.Printf("DELETE login=%s subject=%s", login, subject)
		err = s.deleteMessagesBySubject(login, subject)
		if err != nil {
			writeError(w, 500, "failed to delete message: "+err.Error())
			return
		}
	}

	id := r.FormValue("id")
	if id != "" {
		log.Printf("DELETE login=%s id=%s", login, id)
		err = s.deleteMessagesByID(login, id)
		if err != nil {
			writeError(w, 500, "failed to delete message: "+err.Error())
			return
		}
	}

	writeResponse(w, 200, map[string]interface{}{
		"status": "success",
	})
}
开发者ID:dmage,项目名称:pieceofapp,代码行数:31,代码来源:pownyapp-backend.go

示例7: 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)
	}
}
开发者ID:homburg,项目名称:devd,代码行数:28,代码来源:fileserver_test.go

示例8: pubHandler

func pubHandler(w http.ResponseWriter, req *http.Request) {
	name := req.FormValue("topic")
	if name == "" {
		http.Error(w, "missing topic", 403)
		return
	}
	size, err := strconv.Atoi(req.FormValue("size"))
	if err != nil {
		http.Error(w, err.Error(), 403)
		return
	}

	var (
		msg    *message.Ins
		header message.Header
		msgs   = make([]*message.Ins, 0, size)
	)
	for !logex.Equal(err, io.EOF) {
		msg, err = message.ReadMessage(&header, req.Body, message.RF_DEFAULT)
		if err != nil {
			break
		}
		msgs = append(msgs, msg)
	}

	t, err := getTopic(name)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}
	t.PutSync(msgs)
	w.Write([]byte("hello"))
}
开发者ID:chzyer-dev,项目名称:muxque,代码行数:33,代码来源:server.go

示例9: createUser

func (srv *Server) createUser(w http.ResponseWriter, req *http.Request, reqId string) (interface{}, error) {
	if err := srv.validate(req, []string{"UserName"}); err != nil {
		return nil, err
	}
	path := req.FormValue("Path")
	if path == "" {
		path = "/"
	}
	name := req.FormValue("UserName")
	for _, user := range srv.users {
		if user.Name == name {
			return nil, &iam.Error{
				StatusCode: 409,
				Code:       "EntityAlreadyExists",
				Message:    fmt.Sprintf("User with name %s already exists.", name),
			}
		}
	}
	user := iam.User{
		Id:   "USER" + reqId + "EXAMPLE",
		Arn:  fmt.Sprintf("arn:aws:iam:::123456789012:user%s%s", path, name),
		Name: name,
		Path: path,
	}
	srv.users = append(srv.users, user)
	return iam.CreateUserResp{
		RequestId: reqId,
		User:      user,
	}, nil
}
开发者ID:fsouza,项目名称:go-iam,代码行数:30,代码来源:server.go

示例10: onRequest

func onRequest(w http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	f := &Frame{xrange, yrange}
	{
		v, err := strconv.ParseFloat(req.FormValue("xr"), 64)
		if err == nil {
			f.xrange = v
		}
		v, err = strconv.ParseFloat(req.FormValue("yr"), 64)
		if err == nil {
			f.yrange = v
		}
	}
	i := &Image{width, height}
	{
		v, err := strconv.Atoi(req.FormValue("w"))
		if err == nil {
			i.width = v
		}
		v, err = strconv.Atoi(req.FormValue("h"))
		if err == nil {
			i.height = v
		}
	}
	run(w, f, i)
}
开发者ID:skhal,项目名称:gopl_old,代码行数:26,代码来源:mandelbrot.go

示例11: deleteData

func deleteData(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)
	u := user.Current(ctx)
	keyVal := req.FormValue("keyVal")
	key, err := datastore.DecodeKey(keyVal)
	if err != nil {
		http.Error(res, "Invalid data", http.StatusBadRequest)
		log.Warningf(ctx, err.Error())
		return
	}
	var l list
	err = datastore.Get(ctx, key, &l)
	if err != nil {
		http.Error(res, "Invalid data", http.StatusBadRequest)
		log.Warningf(ctx, err.Error())
		return
	}
	if l.Owner != u.Email {
		http.Error(res, "Not authorized to delete this entry", http.StatusUnauthorized)
		log.Warningf(ctx, err.Error())
		return
	}
	err = datastore.Delete(ctx, key)
	if err != nil {
		http.Error(res, "Server Error", http.StatusInternalServerError)
		log.Errorf(ctx, err.Error())
		return
	}
}
开发者ID:CodingDance,项目名称:GolangTraining,代码行数:29,代码来源:main.go

示例12: newAuthenticatedRequest

func (c *Client) newAuthenticatedRequest(urlToken string, values url.Values) (*http.Request, error) {
	var req *http.Request
	var err error
	switch c.authMethod {
	case AuthMethodClientSecretPost:
		values.Set("client_secret", c.creds.Secret)
		req, err = http.NewRequest("POST", urlToken, strings.NewReader(values.Encode()))
		if err != nil {
			return nil, err
		}
	case AuthMethodClientSecretBasic:
		req, err = http.NewRequest("POST", urlToken, strings.NewReader(values.Encode()))
		if err != nil {
			return nil, err
		}
		encodedID := url.QueryEscape(c.creds.ID)
		encodedSecret := url.QueryEscape(c.creds.Secret)
		req.SetBasicAuth(encodedID, encodedSecret)
	default:
		panic("misconfigured client: auth method not supported")
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	return req, nil

}
开发者ID:40a,项目名称:bootkube,代码行数:26,代码来源:oauth2.go

示例13: foo

func foo(res http.ResponseWriter, req *http.Request) {

	templ, error := template.ParseFiles("tpl.gohtml") // Parse template file
	if error != nil {
		log.Fatalln(error)
	}

	error = templ.Execute(os.Stdout, nil)
	if error != nil {
		log.Fatalln(error)
	}

	cookie, err := req.Cookie("session-fino")

	if err != nil {
		// id, _ := uuid.NewV4()
		cookie = &http.Cookie{
			Name:  "session-fino",
			Value: "0",
			// Secure: true,
			HttpOnly: true,
		}

	}
	count, _ := strconv.Atoi(cookie.Value)
	count++
	cookie.Value = strconv.Itoa(count)
	fmt.Println(cookie)

	http.SetCookie(res, cookie)

	templ.ExecuteTemplate(res, "tpl.gohtml", cookie)

}
开发者ID:mjrmyke,项目名称:GoLangCourse,代码行数:34,代码来源:main.go

示例14: handleOauth2Callback

func handleOauth2Callback(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)
	api := NewGithubAPI(ctx)
	// get the session
	session := getSession(ctx, req)

	state := req.FormValue("state")
	code := req.FormValue("code")

	if state != session.State {
		http.Error(res, "invalid state", 401)
		return
	}

	accessToken, err := api.getAccessToken(state, code)
	if err != nil {
		http.Error(res, err.Error(), 500)
		return
	}
	api.accessToken = accessToken

	username, err := api.getUsername()
	if err != nil {
		http.Error(res, err.Error(), 500)
		return
	}

	session.Username = username
	session.AccessToken = accessToken
	putSession(ctx, res, session)

	delayedGetStats.Call(ctx, accessToken, username)
	http.Redirect(res, req, "/github-info", 302)

}
开发者ID:RaviTezu,项目名称:GolangTraining,代码行数:35,代码来源:login.go

示例15: PortBindingDelete

func PortBindingDelete(w http.ResponseWriter, r *http.Request) {
	params := r.URL.Query()
	port := params.Get(":port")
	host := r.FormValue("host")
	hostPort := r.FormValue("host_port")

	i, binding, err := getPortBinding(port, false)
	if err != nil {
		w.Write([]byte("{\"error\": \"" + err.Error() + "\"}"))
		return
	}

	if binding == nil {
		w.Write([]byte("{}"))
		return
	}
	if host != "" && hostPort != "" {
		binding.RemoveBackend(host, hostPort)
	}
	currentHost, err := h.GetCurrentHost()
	if err != nil {
		w.Write([]byte("{\"error\": \"" + err.Error() + "\"}"))
		return
	}
	if len(binding.Backends) == 0 || (host == "" && hostPort == "") {
		binding.Stop()
		copy(currentHost.PortBindings[i:], currentHost.PortBindings[i+1:])
		currentHost.PortBindings[len(currentHost.PortBindings)-1] = nil
		currentHost.PortBindings = currentHost.PortBindings[:len(currentHost.PortBindings)-1]
	}
	w.Write([]byte("{\"success\": true}"))
	currentHost.Persist()
}
开发者ID:romanoff,项目名称:vanguard,代码行数:33,代码来源:portbinding.go


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