當前位置: 首頁>>代碼示例>>Golang>>正文


Golang Request.Form方法代碼示例

本文整理匯總了Golang中net/http.Request.Form方法的典型用法代碼示例。如果您正苦於以下問題:Golang Request.Form方法的具體用法?Golang Request.Form怎麽用?Golang Request.Form使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在net/http.Request的用法示例。


在下文中一共展示了Request.Form方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: RegisterHandler

func RegisterHandler(w http.ResponseWriter, r *http.Request) {

	r.ParseForm()
	fmt.Println(r.Form())
	fmt.Println(r.FormValue("data"))

	data := r.Header.Get("data")
	bytes := []byte(data)
	var user types.User
	json.Unmarshal(bytes, &user)
	// userData := f.(map[string]interface{})
	// fmt.Println("data: ", userData)

	err := parsing.AddUser(user.FacebookID, user.PublicKey)

	var errorResponse types.ErrorResponse
	if err != nil {
		fmt.Printf("Error adding user: %v\n", err)
		errorResponse = types.ErrorResponse{true, err.Error()}
	} else {
		fmt.Printf("Added user: %v\n", user.FacebookID)
		errorResponse = types.ErrorResponse{false, ""}
	}

	//write json to return here
	b, err := json.Marshal(errorResponse)
	fmt.Fprintf(w, "%s", b)
}
開發者ID:david-cao,項目名稱:Simple-Go-Key-Server,代碼行數:28,代碼來源:routes.go

示例2: indexHandler

func indexHandler(rw http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	if len(req.Form["name"]) > 0 {
		fmt.Fprint(rw, "hello,", req.Form("name")[0])
	} else {
		fmt.Fprint(rw, "hello,world")
	}
}
開發者ID:wcgh,項目名稱:go_read,代碼行數:8,代碼來源:main.go

示例3: TestSessionManagerFree

/**
 *	測試session manager的Free()
 *	測試時間20秒,需要耐心等待
 */
func TestSessionManagerFree(t *testing.T) {
	runtime.GOMAXPROCS(runtime.NumCPU())
	sm := NewSessionManagerAtGCTime(1, true)

	sm.testing = true

	fmt.Println("sm free() testing...:", time.Now(), "\n")

	go func() {

		//	添加http session
		for i := 1; i <= 10; i++ {
			rw := TestImplResponse{}
			req := http.Request{}
			req.RemoteAddr = "128.0.0.1:8212"
			req.Header = make(http.Header, 1)
			req.Form = make(url.Values)
			sm.tempSessMaxlifeTime = int32(i)
			_, err := sm.GetSession(rw, &req, int32(i), false)
			if nil != err {
				fmt.Println("get session error:", err)
			}
		}

		<-time.After(time.Duration(6) * time.Second)
		fmt.Println("session manager start free()...:", time.Now())
		sm.Free()
	}()

	time.Sleep(time.Duration(20) * time.Second)
}
開發者ID:slowfei,項目名稱:leafveingo,代碼行數:35,代碼來源:lv_session_test.go

示例4: slashws

func slashws(w http.ResponseWriter, req *http.Request) {
	// Upgrader.Upgrade() has Origin check if .CheckOrigin is nil
	upgrader := gorillawebsocket.Upgrader{}
	wsconn, err := upgrader.Upgrade(w, req, nil)
	if err != nil { // Upgrade() does http.Error() to the client
		return
	}

	// req.Method == "GET" asserted by the mux
	req.Form = nil // reset reused later .Form
	c := &conn{
		Conn:          wsconn,
		requestOrigin: req,
		receive:       make(chan *received, 2),
		push:          make(chan *pageUpdate, 2),
		full:          defaultClient(),
	}
	register <- c
	defer func() {
		unregister <- c
		c.Conn.Close()
	}()
	stop := make(chan struct{}, 1)
	go c.receiveLoop(stop) // read from the client
	c.updateLoop(stop)     // write to the client
}
開發者ID:tomzhang,項目名稱:golang-devops-stuff,代碼行數:26,代碼來源:ws.go

示例5: Request

func (req *stockHttp) Request(ret interface{}) error {
	var hdl *http.Request
	var resp *http.Response
	var err error

	if hdl, err = http.NewRequest("GET", req.url+"?"+req.params.Encode(), nil); err != nil {
		return err
	}

	hdl.Form = req.params
	if err = hdl.ParseForm(); err != nil {
		return err
	}

	for k, v := range req.headers {
		hdl.Header.Add(k, v)
	}

	if resp, err = http.DefaultClient.Do(hdl); err != nil {
		return err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}

	if err = json.Unmarshal(body, ret); err != nil {
		return err
	}

	return nil
}
開發者ID:heresfan,項目名稱:stockUtils,代碼行數:34,代碼來源:stock_http.go

示例6: ServeHTTP

func (handler *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
	log := handler.logger.Session("index")

	client := handler.clientFactory.Build(r)

	pipelines, err := client.ListPipelines()
	if err != nil {
		log.Error("failed-to-list-pipelines", err)
		return err
	}

	if len(pipelines) == 0 {
		err := handler.noBuildsTemplate.Execute(w, TemplateData{})
		if err != nil {
			log.Fatal("failed-to-build-template", err, lager.Data{})
			return err
		}

		return nil
	}

	if r.Form == nil {
		r.Form = url.Values{}
	}

	r.Form[":pipeline"] = []string{pipelines[0].Name}

	return handler.pipelineHandler.ServeHTTP(w, r)
}
開發者ID:xoebus,項目名稱:checkin,代碼行數:29,代碼來源:handler.go

示例7: run_test_request

func run_test_request(t *testing.T, server *plate.Server, method, url_str string, payload url.Values) (*httptest.ResponseRecorder, http.Request) {

	url_obj, err := url.Parse(url_str)
	if err != nil {
		t.Fatal(err)
	}

	r := http.Request{
		Method: method,
		URL:    url_obj,
	}

	if payload != nil {
		r.URL.RawQuery = payload.Encode()
	}

	if strings.ToUpper(method) == "POST" {
		r.Form = payload
	}

	recorder := httptest.NewRecorder()

	server.ServeHTTP(recorder, &r)

	return recorder, r
}
開發者ID:janiukjf,項目名稱:GoAdmin,代碼行數:26,代碼來源:index_test.go

示例8: encodeBody

func (me *Request) encodeBody(method string) (*http.Request, error) {
	var req *http.Request
	var err error

	//given body is a param collection
	if params, ok := me.body.(map[string]interface{}); ok {
		paramValues := url.Values{}
		for key, val := range params {
			strVal := ToString(val, "")
			if len(strVal) > 0 {
				paramValues.Add(key, strVal)
			}
		}
		req, err = http.NewRequest(method, me.url, nil)
		req.Form = paramValues
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	} else { //given a raw body object
		bodyBytes, err := json.Marshal(me.body)
		if err != nil {
			return nil, errors.New("Invalid JSON in the query")
		}
		reader := bytes.NewReader(bodyBytes)
		req, err = http.NewRequest(method, me.url, reader)
		req.Header.Set("Content-Length", strconv.Itoa(len(string(bodyBytes))))
		req.Header.Set("Content-Type", "application/json; charset=utf-8")
	}

	return req, err
}
開發者ID:varver,項目名稱:unirest-go,代碼行數:29,代碼來源:Request.go

示例9: IndexWS

func IndexWS(access *Access, errlog *log.Logger, minperiod flags.Period, w http.ResponseWriter, req *http.Request) {
	// Upgrader.Upgrade() has Origin check if .CheckOrigin is nil
	upgrader := gorillawebsocket.Upgrader{
		HandshakeTimeout: 5 * time.Second,
	}
	wsconn, err := upgrader.Upgrade(w, req, nil)
	if err != nil { // Upgrade() does http.Error() to the client
		return
	}

	// req.Method == "GET" asserted by the mux
	req.Form = nil // reset reused later .Form
	c := &conn{
		Conn: wsconn,

		requestOrigin: req,

		receive: make(chan *received, 2),
		pushch:  make(chan *IndexUpdate, 2),
		para:    params.NewParams(minperiod),
		access:  access,
	}
	Register <- c
	defer func() {
		unregister <- c
		c.Conn.Close()
	}()
	stop := make(chan struct{}, 1)
	go c.receiveLoop(stop)     // read from the client
	c.updateLoop(errlog, stop) // write to the client
}
開發者ID:vadv,項目名稱:ostent,代碼行數:31,代碼來源:ws.go

示例10: benchRequest

func benchRequest(b *testing.B, router http.Handler, r *http.Request) {
	w := mockResponseWriter{}
	u := r.URL
	r.RequestURI = u.RequestURI()

	b.ReportAllocs()
	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		router.ServeHTTP(&w, r)

		// clear caches
		r.Form = nil
		r.PostForm = nil
		r.MultipartForm = nil
	}
}
開發者ID:najeira,項目名稱:go-frameworks-benchmark,代碼行數:17,代碼來源:main.go

示例11: TestFilter_Request

func TestFilter_Request(t *testing.T) {
	print("Filter_Request\n")
	c := gsc(t)
	gl, err := c.Games()
	assert.Nil(t, err, "c.Games()")
	r := http.Request{}
	uv := url.Values{}
	uv.Add("dummy", "dummy")
	r.Form = uv
	assert.Equal(t, len(Filter(gl).Request(&r)), 801, "FilterRequest()")
	uv.Add("has", "true")
	assert.Equal(t, len(Filter(gl).Request(&r)), 1, "FilterRequest(has=true)")
	uv.Del("has")
	uv.Add("manual", "true")
	assert.Equal(t, len(Filter(gl).Request(&r)), 1, "FilterRequest(manual=true)")
	uv.Del("manual")
	uv.Add("box", "true")
	assert.Equal(t, len(Filter(gl).Request(&r)), 1, "FilterRequest(box=true)")
}
開發者ID:ChrisKaufmann,項目名稱:gameslist,代碼行數:19,代碼來源:game_test.go

示例12: findHandler

// findHandler ...
func (router *Router) findHandler(req *http.Request) http.HandlerFunc {
	if methodes, ok := router.routes[req.Method]; ok {
		if handler, ok := methodes[req.URL.Path]; ok {
			return handler
		}
	}
	if methods, ok := router.regexps[req.Method]; ok {
		for exp, handler := range methods {
			if exp.MatchString(req.URL.Path) {
				matched := exp.FindAllStringSubmatch(req.URL.Path, -1)
				if req.Form == nil {
					req.Form = url.Values{}
				}
				for i, name := range exp.SubexpNames() {
					req.Form.Add(name, matched[0][i])
				}
				return handler
			}
		}
	}
	return nil
}
開發者ID:otiai10,項目名稱:marmoset,代碼行數:23,代碼來源:router.go

示例13: ServeHTTP

func (s *ChatServer) ServeHTTP(rep http.ResponseWriter, req *http.Request) {
	//短連接要調用一下這個,否則go不會主動斷開連接
	//req.ParseForm();
	req.Form = make(url.Values)

	body, e := ioutil.ReadAll(req.Body)
	if e != nil {
		fmt.Printf("read request error\n")
	} else {
		sessionid := req.Header.Get("SESSIONID")
		event := req.Header.Get("EVENT")
		fmt.Printf("sid=%s, event=%s\n", sessionid, event)
		switch event {
		case "1": //新連接
			//TODO
		case "2": //連接關閉
			s.logout(sessionid)
		default: //消息處理
			if len(body) > 0 {
				js, err := simplejson.NewJson(body)
				if err != nil {
					fmt.Printf("parse JSON error, data=")
					fmt.Println(body)
				} else {
					r := s.handle(sessionid, js)
					if len(r) > 0 {
						rep.Header().Add("Content-Length", strconv.Itoa(len(r)))
						rep.Write(r)
					} else {
						fmt.Println("no message response")
					}
				}
			}
		}
	}

	//rep.Write([]byte("<h1>Hello World</h1>"))
}
開發者ID:eastlhu,項目名稱:fooking,代碼行數:38,代碼來源:gateway.go

示例14: appendTokenToForm

func appendTokenToForm(r *http.Request, t *jwt.Token, prefix string) error {

	if r.Method == "POST" || r.Method == "PUT" || r.Method == "PATCH" {
		if err := r.ParseForm(); err != nil {
			return err
		}
	}

	if r.Form == nil {
		r.Form = make(url.Values)
	}

	for k, v := range t.Claims {
		vs, err := cast.ToStringE(v)
		if err == nil {
			r.Form.Add(prefix+k, vs)
		} else {
			return errgo.Newf("appendTokenToForm: failed to assert to type string: key %s => value %v : %s", k, v, err.Error())
		}
	}

	return nil
}
開發者ID:hafeez3000,項目名稱:csfw,代碼行數:23,代碼來源:manager.go

示例15: Handler

// Handler returns the handler to use for the given request, consulting r.Method
// and r.URL.Path. It always returns a non-nil handler. If there is no registered handler
// that applies to the request, Handler returns a “page not found” handler and empty pattern.
// If there is a registered handler but requested method is not allowed,
// "method not allowed" and a pattern are returned.
func (t *Router) Handler(r *http.Request) (handler http.Handler, pattern string) {
	// Make sure we have a handler for this request.
	obj, params, found := t.data.Lookup(r.URL.Path)
	if !found {
		return http.HandlerFunc(NotFound), ""
	}

	// Check whether requested method is allowed.
	route := obj.(*Route)
	handler, i := route.Handlers.Get(r.Method)
	if i == -1 {
		return http.HandlerFunc(MethodNotAllowed), route.Pattern
	}

	// Add parameters of request to request.Form and return a handler.
	if len(params) > 0 {
		r.Form = make(url.Values, len(params))
		for i := range params {
			r.Form[params[i].Name] = []string{params[i].Value}
		}
	}
	return handler, route.Pattern
}
開發者ID:colegion,項目名稱:contrib,代碼行數:28,代碼來源:denco.go


注:本文中的net/http.Request.Form方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。