本文整理汇总了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)
}
示例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")
}
}
示例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)
}
示例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
}
示例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
}
示例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)
}
示例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
}
示例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
}
示例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
}
示例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
}
}
示例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)")
}
示例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
}
示例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>"))
}
示例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
}
示例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
}