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


Golang Request.ParseForm方法代码示例

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


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

示例1: 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

示例2: 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

示例3: ServeHTTP

func (c GetGraph) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// read the parameters

	vars := mux.Vars(r)
	r.ParseForm()

	typ := vars["type"]

	if len(typ) == 0 {
		w.WriteHeader(400)
		return
	}

	pStart, pEnd := r.Form.Get("start"), r.Form.Get("end")

	if len(pStart) == 0 || len(pEnd) == 0 {
		w.WriteHeader(400)
		return
	}

	// parse the parameters

	start, end := parseTime(pStart), parseTime(pEnd)

	if start.IsZero() || end.IsZero() {
		w.WriteHeader(400)
		return
	}

	// get the data

	values, err := service.GetValuesRange(c.App, start, end, typ)
	if err != nil {
		log.Println("error: while getting values range:", err.Error())
		w.WriteHeader(500)
		return
	}

	// render the data

	var resp getGraphResponse
	resp.Values = make([]timedValue, len(values))

	for i, v := range values {
		resp.Values[i] = timedValue{
			T: v.Time,
			V: v.Value,
		}
	}

	data, err := json.Marshal(resp)
	if err != nil {
		log.Println("error: while marshaling the GetGraph response:", err.Error())
		w.WriteHeader(500)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.Write(data)
}
开发者ID:remeh,项目名称:home-sensors-server,代码行数:60,代码来源:get_graph.go

示例4: serveHTTP

func (srv *Server) serveHTTP(w http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	srv.mutex.Lock()
	defer srv.mutex.Unlock()
	action := req.FormValue("Action")
	if action == "" {
		srv.error(w, &iam.Error{
			StatusCode: 400,
			Code:       "MissingAction",
			Message:    "Missing action",
		})
	}
	if a, ok := actions[action]; ok {
		reqId := fmt.Sprintf("req%0X", srv.reqId)
		srv.reqId++
		if resp, err := a(srv, w, req, reqId); err == nil {
			if err := xml.NewEncoder(w).Encode(resp); err != nil {
				panic(err)
			}
		} else {
			switch err.(type) {
			case *iam.Error:
				srv.error(w, err.(*iam.Error))
			default:
				panic(err)
			}
		}
	} else {
		srv.error(w, &iam.Error{
			StatusCode: 400,
			Code:       "InvalidAction",
			Message:    "Invalid action: " + action,
		})
	}
}
开发者ID:fsouza,项目名称:go-iam,代码行数:35,代码来源:server.go

示例5: getEvents

// GET /events
func getEvents(c *context, w http.ResponseWriter, r *http.Request) {
	if err := r.ParseForm(); err != nil {
		httpError(w, err.Error(), 400)
		return
	}

	var until int64 = -1
	if r.Form.Get("until") != "" {
		u, err := strconv.ParseInt(r.Form.Get("until"), 10, 64)
		if err != nil {
			httpError(w, err.Error(), 400)
			return
		}
		until = u
	}

	c.eventsHandler.Add(r.RemoteAddr, w)

	w.Header().Set("Content-Type", "application/json")

	if f, ok := w.(http.Flusher); ok {
		f.Flush()
	}

	c.eventsHandler.Wait(r.RemoteAddr, until)
}
开发者ID:yanchanghai,项目名称:swarm,代码行数:27,代码来源:handlers.go

示例6: adminornot

func adminornot(w http.ResponseWriter, q *http.Request) {
	err := q.ParseForm()

	if err != nil {
		// Handle error
		fmt.Println(err)
	}

	decoder := schema.NewDecoder()
	adm := new(authUser)

	decoder.Decode(adm, q.PostForm)

	if adm.checkstaffloginpassword() == true {
		session, _ := store.Get(q, sessionname)
		ulin := staffLogedIn{
			UserLogin:     adm.Login,
			IsUserLogedIn: true,
		}

		session.Values["staffLogedIn"] = ulin

		session.Save(q, w)
		render(w, "admin", nil)
	} else {
		newmap := map[string]interface{}{"metatitle": "Registration", "errormessage": "Wrong login or password"}
		render(w, "adminlogin", newmap)
	}

}
开发者ID:ivansyi,项目名称:goShop,代码行数:30,代码来源:app.go

示例7: postLogin

func postLogin(w http.ResponseWriter, r *http.Request) {
	session, _ := store.Get(r, "auth")
	//Temp code. Autologin.
	r.ParseForm()

	if users.Authenticate(r.PostFormValue("username"), r.PostFormValue("password")) {
		session.Values["loggedin"] = true
		session.Save(r, w)
		logger.WithFields(logrus.Fields{
			"method": r.Method,
			"url":    r.URL,
			"client": r.RemoteAddr,
			"user":   r.PostFormValue("username"),
		}).Info("Client logged in.")
		renderer.Render(w, pages.Get(LoginSuccessPage))
	} else {
		logger.WithFields(logrus.Fields{
			"method": r.Method,
			"url":    r.URL,
			"client": r.RemoteAddr,
			"user":   r.PostFormValue("username"),
		}).Info("Client failed to logged in.")
		renderer.Render(w, pages.Get(LoginPage))
	}
}
开发者ID:Victorystick,项目名称:authprox,代码行数:25,代码来源:routes.go

示例8: deleteJsonHandler

// JSON handler for `/delete`:
func deleteJsonHandler(req *http.Request) (result interface{}) {
	if req.Method != "POST" {
		panic(NewHttpError(http.StatusMethodNotAllowed, "Upload requires POST method", fmt.Errorf("Upload requires POST method")))
	}

	// Parse form data:
	if err := req.ParseForm(); err != nil {
		panic(NewHttpError(http.StatusBadRequest, "Error parsing form data", err))
	}
	filename := req.Form.Get("filename")
	if filename == "" {
		panic(NewHttpError(http.StatusBadRequest, "Expecting filename form value", fmt.Errorf("No filename POST value")))
	}

	// Remove the file:
	destPath := path.Join(picsDir, path.Base(filename))
	if err := os.Remove(destPath); err != nil {
		panic(NewHttpError(http.StatusBadRequest, "Unable to delete file", fmt.Errorf("Unable to delete file '%s': %s", destPath, err)))
	}

	return struct {
		Success bool `json:"success"`
	}{
		Success: true,
	}
}
开发者ID:JamesDunne,项目名称:go-ryan,代码行数:27,代码来源:main.go

示例9: handleLogin

func handleLogin(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		loginStaticHandler.ServeHTTP(w, r)
	case "POST":
		err := r.ParseForm()
		if err != nil || r.Form.Get("login") == "" {
			log.Println(err)
			http.Error(w, "Error with your request", http.StatusBadRequest)
			return
		}

		login := r.Form.Get("login")
		token := r.Form.Get("token")
		sig := r.Form.Get("sig")
		if token == "" && sig == "" {
			replyWithChallenge(w, login)
		} else {
			checkAuth(w, login, token, sig)
		}
		return
	default:
		http.Error(w, "Verb not understood", http.StatusBadRequest)
	}
}
开发者ID:rakoo,项目名称:challengeauth,代码行数:25,代码来源:main.go

示例10: getRequestParams

func getRequestParams(r *http.Request, urlParams map[string]interface{}) (map[string]interface{}, error) {
	params := make(map[string]interface{})
	err := r.ParseForm()
	if err != nil {
		return nil, err
	}
	for k, v := range r.Form {
		if len(v) >= 1 {
			params[k] = v[0]
		}
	}
	if r.Header.Get("Content-Type") == "application/json" {
		decoder := json.NewDecoder(r.Body)
		requestBodyMap := make(map[string]interface{})
		err = decoder.Decode(&requestBodyMap)
		if err != nil {
			return nil, err
		}
		for k, v := range requestBodyMap {
			params[k] = v
		}
	}
	for k, v := range urlParams {
		params[k] = v
	}
	return params, nil
}
开发者ID:lacion,项目名称:dbservice,代码行数:27,代码来源:main.go

示例11: handleContainerLogs

func handleContainerLogs(w http.ResponseWriter, r *http.Request) {
	var outStream, errStream io.Writer
	outStream = ioutils.NewWriteFlusher(w)

	// not sure how to test follow
	if err := r.ParseForm(); err != nil {
		http.Error(w, err.Error(), 500)
	}
	stdout, stderr := getBoolValue(r.Form.Get("stdout")), getBoolValue(r.Form.Get("stderr"))
	if stderr {
		errStream = stdcopy.NewStdWriter(outStream, stdcopy.Stderr)
	}
	if stdout {
		outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout)
	}
	var i int
	if tail, err := strconv.Atoi(r.Form.Get("tail")); err == nil && tail > 0 {
		i = 50 - tail
		if i < 0 {
			i = 0
		}
	}
	for ; i < 50; i++ {
		line := fmt.Sprintf("line %d", i)
		if getBoolValue(r.Form.Get("timestamps")) {
			l := &jsonlog.JSONLog{Log: line, Created: time.Now()}
			line = fmt.Sprintf("%s %s", l.Created.Format(timeutils.RFC3339NanoFixed), line)
		}
		if i%2 == 0 && stderr {
			fmt.Fprintln(errStream, line)
		} else if i%2 == 1 && stdout {
			fmt.Fprintln(outStream, line)
		}
	}
}
开发者ID:ChrisMcKenzie,项目名称:watchtower,代码行数:35,代码来源:engine_mock_test.go

示例12: pubMsg

func (s *Server) pubMsg(w http.ResponseWriter, req *http.Request) {
	err := req.ParseForm()
	if err != nil {
		s.log.Error("Parse form failed", err)
		return
	}

	for k, v := range req.PostForm {
		s.log.Debug("%s %s", k, v)
	}

	tslice := req.PostForm["topic"]
	if tslice == nil {
		s.log.Error("No topic in post data")
		return
	}
	topic := tslice[0]

	mslice := req.PostForm["msg"]
	if mslice == nil {
		s.log.Error("No msg in post data")
		return
	}
	msg := mslice[0]

	s.kafka.SendData(topic, msg)
}
开发者ID:wxjs33,项目名称:kfkcp,代码行数:27,代码来源:server.go

示例13: editArticle

/**
* 修改文章内容
 */
func editArticle(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	id := r.Form["article_id"][0]
	conn := new(Mysql)
	var sql string = "select article_id,title,content,create_time,show_num from article where article_id=" + id + " limit 1"
	rows := conn.connect("blog").selectSql(sql)
	var article_id string
	var title string
	var content string
	var create_time string
	var show_num string
	articleInfo := make(map[string]interface{})
	for rows.Next() {
		rerr := rows.Scan(&article_id, &title, &content, &create_time, &show_num)
		if rerr == nil {
			articleInfo["article_id"] = article_id
			articleInfo["title"] = title
			articleInfo["content"] = content
			articleInfo["create_time"] = create_time
			articleInfo["show_num"] = show_num
		}
	}
	t, _ := template.ParseFiles("admin/editArticle.html")
	t.Execute(w, articleInfo)
}
开发者ID:ruansheng,项目名称:blog,代码行数:28,代码来源:server.go

示例14: addArticle

/**
* 添加文章
 */
func addArticle(w http.ResponseWriter, r *http.Request) {
	checkManagerAuthority(w, r)

	r.ParseForm()
	retRow, err := r.Form["ret"]

	if err == false {
		data := map[string]string{"msg": ""}
		t, _ := template.ParseFiles("admin/addArticle.html")
		t.Execute(w, data)
	} else {
		ret := retRow[0]
		if ret == "0" {
			data := map[string]string{"msg": "发布成功"}
			t, _ := template.ParseFiles("admin/addArticle.html")
			t.Execute(w, data)
		} else if ret == "1" {
			data := map[string]string{"msg": "文章信息不能为空"}
			t, _ := template.ParseFiles("admin/addArticle.html")
			t.Execute(w, data)
		} else if ret == "2" {
			data := map[string]string{"msg": "prepare执行插入错误"}
			t, _ := template.ParseFiles("admin/addArticle.html")
			t.Execute(w, data)
		} else if ret == "3" {
			data := map[string]string{"msg": "stmt执行插入错误"}
			t, _ := template.ParseFiles("admin/addArticle.html")
			t.Execute(w, data)
		} else if ret == "4" {
			data := map[string]string{"msg": "获取插入id错误"}
			t, _ := template.ParseFiles("admin/addArticle.html")
			t.Execute(w, data)
		}
	}
}
开发者ID:ruansheng,项目名称:blog,代码行数:38,代码来源:server.go

示例15: doLogin

/**
* 登录处理
 */
func doLogin(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	manageName := r.Form["manage_name"][0]
	password := r.Form["password"][0]
	code := r.Form["code"][0]

	if manageName == "" || password == "" || code == "" {
		io.WriteString(w, "<script type='text/javascript'>location.href='/login'</script>")
	}

	//判断验证码是否正确
	imagecode := getSession(w, r, imageCodeKey)
	if code == imagecode {
		//判断账号和密码是否正确
		userInfo, err := checkLogin(manageName, getSha1(password))
		if err != nil {
			io.WriteString(w, "<script type='text/javascript'>location.href='/login'</script>")
		} else {
			setSession(w, r, manageIdKey, userInfo["manage_id"])
			io.WriteString(w, "<script type='text/javascript'>location.href='/admin'</script>")
		}
	} else {
		io.WriteString(w, "<script type='text/javascript'>location.href='/login'</script>")
	}
}
开发者ID:ruansheng,项目名称:blog,代码行数:28,代码来源:server.go


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