• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang schema.NewDecoder函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: main

func main() {
	u, _ := url.Parse("something.com/samer")
	uq, _ := url.Parse(u.String() + "?blahblah=ya")
	var q1 blahQuery
	log.Println(schema.NewDecoder().Decode(&q1, u.Query()))
	log.Println(q1)
	var q2 blahQuery
	log.Println(schema.NewDecoder().Decode(&q2, uq.Query()))
	log.Println(q2)
	uqq, _ := url.Parse(uq.String() + "&lala=yo")
	var q3 blahQuery
	log.Println(schema.NewDecoder().Decode(&q3, uqq.Query()))
	log.Println(q3)
}
开发者ID:samertm,项目名称:play,代码行数:14,代码来源:main.go


示例2: main

func main() {
	db := sqlx.MustOpen("sqlite3", ":memory:")

	db.MustExec(`CREATE TABLE Products (
                        id INTEGER PRIMARY KEY, 
                        name TEXT
                );
                INSERT INTO Products VALUES (1, 'TV');
                INSERT INTO Products VALUES (2, 'Microwave');`)

	inventory := &DatabaseInventoryRepository{db}

	env := &Env{
		inventory: inventory,
		decoder:   schema.NewDecoder(),
	}

	r := mux.NewRouter()

	r.Handle("/products", handlers.LoggingHandler(os.Stdout, Handler{env, ProductsHandler}))
	r.Handle("/products/search", handlers.LoggingHandler(os.Stdout, Handler{env, SearchHandler}))
	r.Handle("/docs/", http.StripPrefix("/docs/", http.FileServer(http.Dir("docs"))))

	http.ListenAndServe(":8080", r)
}
开发者ID:dimiro1,项目名称:experiments,代码行数:25,代码来源:main.go


示例3: commandHandler

func commandHandler(res http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	command := new(SlackCommand)
	decoder := schema.NewDecoder()

	err := decoder.Decode(command, req.PostForm)
	if err != nil {
		res.WriteHeader(400)
		io.WriteString(res, "Invalid form data\n")
		return
	}

	if command.Token != config.IncomingToken {
		res.WriteHeader(403)
		io.WriteString(res, "Invalid token\n")
		return
	}

	user, created := userStore.GetOrAdd(command.UserID)
	if created {
		user.UserName = command.UserName
	}

	commandFunc, exists := commands[command.getSubCommand()]
	if !exists {
		commandFunc = commands["help"]
	}
	err = commandFunc(command, user)
	if err != nil {
		res.WriteHeader(400)
		io.WriteString(res, err.Error())
	}
}
开发者ID:arjandepooter,项目名称:slack-exact,代码行数:33,代码来源:handlers.go


示例4: create

// create creates a new user in the system.
func (u userAdminForm) create(request *http.Request) error {
	err := request.ParseForm()

	if err != nil {
		return err
	}

	decoder := schema.NewDecoder()
	form := new(userAdminForm)

	err = decoder.Decode(form, request.PostForm)

	if err != nil {
		return err
	}

	_, err = database.CreateUser(
		form.Email,
		form.FirstName,
		form.LastName,
		form.Password,
		form.Admin,
	)

	return err
}
开发者ID:francoishill,项目名称:leeroyci,代码行数:27,代码来源:user_admin.go


示例5: HandleRawRequest

func (gmo *GMO) HandleRawRequest(action string, params url.Values, output interface{}) (err error) {
	if gmo.Debug {
		log.Println("GMO Request [Debug]:", gmo.Endpoint+action)
	}
	resp, err := http.PostForm(gmo.Endpoint+action, params)
	if err != nil {
		return
	}
	bytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}
	results, err := url.ParseQuery(string(bytes))
	if err != nil {
		return
	}

	decoder := schema.NewDecoder()
	decoder.IgnoreUnknownKeys(true)
	errd := decoder.Decode(output, results)

	if code := results.Get("ErrCode"); code != "" {
		err = fmt.Errorf("%v: %s", code, results.Get("ErrInfo"))
		return
	}

	if errd != nil {
		err = errd
	}

	return
}
开发者ID:Acidburn0zzz,项目名称:gmo,代码行数:32,代码来源:gmo.go


示例6: noteUpdateHandler

func noteUpdateHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	apiApplyCorsHeaders(w, r)

	// Authenticate
	user := apiAuthenticateUser(r)

	// Find the note or share
	noteIDStr := mux.Vars(r)["id"]
	noteID, _ := strconv.ParseInt(noteIDStr, 10, 64)
	note := findNoteByID(noteID)
	share := findShareByAuthKey(noteIDStr)

	if share != nil {
		note = findNoteByID(int64(share.NoteID))
	} else if user == nil {
		w.WriteHeader(http.StatusForbidden)
		return
	}

	if share != nil && share.Permissions != "readwrite" {
		w.WriteHeader(http.StatusForbidden)
		return
	}

	// Note not found or invalid owner
	if note == nil || (user != nil && note.UserID != user.ID) {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	err := r.ParseForm()
	checkErr(err, "parsing form")

	noteParameters := new(noteRequestParameters)
	decoder := schema.NewDecoder()
	err = decoder.Decode(noteParameters, r.PostForm)
	checkErr(err, "decoding note create")

	var errors []APIError

	// Validate Title
	if len(noteParameters.Title) == 0 {
		errors = append(errors, APIError{Field: "title", Message: "is required"})
	}

	// Validate Body
	if len(noteParameters.Body) == 0 {
		errors = append(errors, APIError{Field: "body", Message: "is required"})
	}

	if len(errors) > 0 {
		apiErrorHandler(w, r, http.StatusBadRequest, errors)
		return
	}

	note.Update(noteParameters.Title, noteParameters.Body)

	w.Write(noteJSON(note))
}
开发者ID:LastZactionHero,项目名称:graynote_server,代码行数:60,代码来源:note_api.go


示例7: ServeHTTP

func (lqa *LiveQA) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()

	if err != nil {
		log.Println(err)
		return
	}

	q := &Question{}
	decoder := schema.NewDecoder()
	err = decoder.Decode(q, r.Form)
	if err != nil {
		log.Println(err)
		return
	}
	q.ReceivedTime = time.Now()

	// Drop query if without a proper Qid
	if len(q.Qid) == 0 {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	log.Println("IP", r.RemoteAddr, "QID", q.Qid)

	// Process query here
	a := lqa.ProcessQuestion(q)

	log.Println("Got answer `", a.Answer.Content, "` for", q.Qid, "in time", a.Answer.Time)

	fmt.Fprintf(w, "%s%s\n", xml.Header, a)
}
开发者ID:eviyulianti,项目名称:trec-liveqa-server,代码行数:31,代码来源:handler.go


示例8: CommandHandler

func CommandHandler(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	hook := r.URL.Path == "/slack_hook"
	if err == nil {
		decoder := schema.NewDecoder()
		command := new(robots.SlashCommand)
		err := decoder.Decode(command, r.PostForm)
		if err != nil {
			log.Println("Couldn't parse post request:", err)
		}
		if hook {
			c := strings.Split(command.Text, " ")
			command.Command = c[1]
			command.Text = strings.Join(c[2:], " ")
		} else {
			command.Command = command.Command[1:]
		}
		robot := GetRobot(command.Command)
		w.WriteHeader(http.StatusOK)
		if robot != nil {
			if hook {
				JSONResp(w, robot.Run(command))
			} else {
				plainResp(w, robot.Run(command))
			}
		} else {
			r := "No robot for that command yet :("
			if hook {
				JSONResp(w, r)
			} else {
				plainResp(w, r)
			}
		}
	}
}
开发者ID:JamesEVerhagen,项目名称:slackbot,代码行数:35,代码来源:main.go


示例9: newPost

func (controller *usersController) newPost(rw http.ResponseWriter, req *http.Request) (int, error) {
	err := req.ParseForm()
	if err != nil {
		return http.StatusInternalServerError, err
	}

	decoder := schema.NewDecoder()
	// Ignore unknown keys to prevent errors from the CSRF token.
	decoder.IgnoreUnknownKeys(true)
	formUser := new(viewmodels.UsersEditViewModel)
	err = decoder.Decode(formUser, req.PostForm)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	valErrors := validateUserForm(formUser, false)
	if len(valErrors) > 0 {
		isAuthenticated, user := getCurrentUser(rw, req, controller.authorizer)
		vm := viewmodels.NewUserViewModel(formUser, controller.roles, isAuthenticated, user, valErrors)
		vm.CsrfField = csrf.TemplateField(req)
		return http.StatusOK, controller.newTemplate.Execute(rw, vm)
	}

	var user httpauth.UserData
	user.Username = formUser.Username
	user.Email = formUser.Email
	password := formUser.Password
	user.Role = formUser.Role
	err = controller.authorizer.Register(rw, req, user, password)
	if err != nil {
		return http.StatusInternalServerError, err
	}
	http.Redirect(rw, req, "/settings/users", http.StatusSeeOther)
	return http.StatusSeeOther, nil
}
开发者ID:turnkey-commerce,项目名称:go-ping-sites,代码行数:35,代码来源:users.go


示例10: HandleBalancerCreate

func HandleBalancerCreate(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		http.Error(w, "Bad Request", http.StatusBadRequest)
		return
	}
	body := struct {
		Label string `schema:"label"`
	}{}
	err = schema.NewDecoder().Decode(&body, r.PostForm)
	if err != nil {
		http.Error(w, "Bad Request", http.StatusBadRequest)
		return
	}

	bal := data.Balancer{}
	bal.Label = body.Label
	err = bal.Put()
	if err != nil {
		panic(err)
	}

	err = feline.Commit(&bal)
	if err != nil {
		panic(err)
	}

	http.Redirect(w, r, "/balancers/"+bal.Id.Hex()+"/edit", http.StatusSeeOther)
}
开发者ID:zotgene,项目名称:loadcat,代码行数:29,代码来源:balancers.go


示例11: TestPullRequestsService_Get

func TestPullRequestsService_Get(t *testing.T) {
	setup()
	defer teardown()

	want := &PullRequest{PullRequest: github.PullRequest{Number: github.Int(1)}}
	opts := &PullRequestGetOptions{Checklist: true}

	var called bool
	mux.HandleFunc(urlPath(t, router.RepoPullRequest, map[string]string{"RepoSpec": "r.com/x", "Pull": "1"}), func(w http.ResponseWriter, r *http.Request) {
		called = true
		testMethod(t, r, "GET")

		var gotOpts PullRequestGetOptions
		schema.NewDecoder().Decode(&gotOpts, r.URL.Query())
		if !reflect.DeepEqual(&gotOpts, opts) {
			t.Errorf("got requested opts %+v, but got %+v", &gotOpts, opts)
		}

		writeJSON(w, want)
	})

	pull, _, err := client.PullRequests.Get(PullRequestSpec{Repo: RepoSpec{URI: "r.com/x"}, Number: 1}, opts)
	if err != nil {
		t.Errorf("PullRequests.Get returned error: %v", err)
	}

	if !called {
		t.Fatal("!called")
	}

	if !reflect.DeepEqual(pull, want) {
		t.Errorf("PullRequests.Get returned %+v, want %+v", pull, want)
	}
}
开发者ID:keegancsmith,项目名称:go-sourcegraph,代码行数:34,代码来源:pulls_test.go


示例12: decodePerson

func decodePerson(r *http.Request) *person.Person {
	// Decode the form data and add the resulting Person type to the Profile.
	p := &person.Person{}
	decoder := schema.NewDecoder()
	decoder.Decode(p, r.Form)
	return p
}
开发者ID:gaego,项目名称:auth,代码行数:7,代码来源:provider.go


示例13: TestEncodeDecodeQuery

func TestEncodeDecodeQuery(t *testing.T) {

	const expected = "entities=c%2F1&entities=c%2F2&origin=mysystem"

	q := Query{}
	q.Origin = "mysystem"
	q.Entities = []string{"c/1", "c/2"}

	v, err := query.Values(q)

	if err != nil {
		t.Fatal(err)
	}

	t.Log(v.Encode())

	if v.Encode() != expected {
		t.Fatalf("Expected %s, got %s", expected, v.Encode())
	}

	q2 := new(Query)
	decoder := schema.NewDecoder()
	err = decoder.Decode(q2, v)

	if err != nil {
		t.Fatal(err)
	}

	if q.Origin != q2.Origin {
		t.Fatalf("Expected %s, got %s", q.Origin, q2.Origin)
	}
}
开发者ID:straumur,项目名称:straumur,代码行数:32,代码来源:query_test.go


示例14: post

func (controller *profileController) post(rw http.ResponseWriter, req *http.Request) (int, error) {
	err := req.ParseForm()
	if err != nil {
		return http.StatusInternalServerError, err
	}

	decoder := schema.NewDecoder()
	// Ignore unknown keys to prevent errors from the CSRF token.
	decoder.IgnoreUnknownKeys(true)
	formUser := new(viewmodels.ProfileEditViewModel)
	err = decoder.Decode(formUser, req.PostForm)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	valErrors := validateProfileForm(formUser, true)
	if len(valErrors) > 0 {
		isAuthenticated, user := getCurrentUser(rw, req, controller.authorizer)
		vm := viewmodels.EditProfileViewModel(formUser, isAuthenticated, user, valErrors)
		vm.CsrfField = csrf.TemplateField(req)
		return http.StatusOK, controller.template.Execute(rw, vm)
	}

	// Update the user.
	err = controller.authorizer.Update(rw, req, "", formUser.Password, formUser.Email)
	if err != nil {
		return http.StatusInternalServerError, err
	}
	http.Redirect(rw, req, "/", http.StatusSeeOther)
	return http.StatusSeeOther, nil
}
开发者ID:turnkey-commerce,项目名称:go-ping-sites,代码行数:31,代码来源:profile.go


示例15: init

func init() {

	beanCh = make(chan []byte, 200)

	decoder = schema.NewDecoder()
	decoder.ZeroEmpty(true)
	decoder.IgnoreUnknownKeys(true)
	decoder.RegisterConverter(Latency(0), func(v string) reflect.Value {
		i, err := strconv.Atoi(v)
		if err != nil {
			l := Latency(0)
			return reflect.ValueOf(l)
		}
		l := Latency(i)
		return reflect.ValueOf(l)
	})

	pn := []string{"10.220.0.0/24", "207.171.3.0/27"}
	for _, p := range pn {
		_, ipnet, err := net.ParseCIDR(p)
		if err != nil {
			panic(err)
		}
		localNets = append(localNets, ipnet)
	}
}
开发者ID:abh,项目名称:v6test,代码行数:26,代码来源:main.go


示例16: create

func (c commandAdminForm) create(request *http.Request, repo *database.Repository) error {
	err := request.ParseForm()

	if err != nil {
		return err
	}

	decoder := schema.NewDecoder()
	form := new(commandAdminForm)

	err = decoder.Decode(form, request.PostForm)

	if err != nil {
		return err
	}

	_, err = database.CreateCommand(
		repo,
		form.Name,
		form.Execute,
		form.Branch,
		form.Kind,
	)

	return err
}
开发者ID:francoishill,项目名称:leeroyci,代码行数:26,代码来源:command_admin.go


示例17: init

func init() {
	Decoder = schema.NewDecoder()
	RegisterMeatHandlers(route.Router)
	RegisterUserHandlers(route.Router)
	http.Handle("/static/",
		http.StripPrefix("/static/", http.FileServer(http.Dir("resources/static/"))))
}
开发者ID:stevemlayton,项目名称:archive-utils,代码行数:7,代码来源:handlers.go


示例18: doInit

func doInit(projectName, appName string, requireConfig bool, logFormatterFactory LogFormatterFactory) *App {
	app := &App{
		common: common{
			Decoder: schema.NewDecoder(),
		},
		AppName:             appName,
		ProjectName:         projectName,
		GorillaRouter:       mux.NewRouter(),
		wantReq:             make(chan *wantReq),
		doneReq:             make(chan *Req),
		getReqs:             make(chan chan *Req),
		getStats:            make(chan chan AppStats),
		loggerMap:           make(map[string]int),
		logFormatterFactory: logFormatterFactory,
	}

	app.loadAppConfigFile(requireConfig)

	// Linux setuid() doesn't work with threaded procs :-O
	// and the go runtime threads before we can get going.
	//
	// http://homepage.ntlworld.com/jonathan.deboynepollard/FGA/linux-thread-problems.html
	//    app.setUserAndGroup()

	app.initLogging()

	maxProcs, _ := app.Cfg.GetInt("gop", "maxprocs", 4*runtime.NumCPU())
	app.Debug("Setting maxprocs to %d", maxProcs)
	runtime.GOMAXPROCS(maxProcs)

	app.initStatsd()

	return app
}
开发者ID:cocoonlife,项目名称:gop,代码行数:34,代码来源:gop.go


示例19: decodeRequestQuery

// decodeRequestQuery decodes a request form.
func decodeRequestQuery(r *http.Request, v interface{}) error {
	if err := schema.NewDecoder().Decode(v, r.URL.Query()); err != nil {
		log.WithField("err", err).Info("Invalid request query")
		return err
	}
	return nil
}
开发者ID:PepperSalt42,项目名称:api,代码行数:8,代码来源:http.go


示例20: authenticate

func (l loginForm) authenticate(request *http.Request) (string, error) {
	err := request.ParseForm()

	if err != nil {
		return "", err
	}

	decoder := schema.NewDecoder()
	form := new(loginForm)

	err = decoder.Decode(form, request.PostForm)

	if err != nil {
		return "", err
	}

	user, err := database.GetUser(form.Email)

	if err != nil {
		return "", err
	}

	auth := database.ComparePassword(form.Password, user.Password)

	if auth == false {
		return "", errors.New("Username and password do not match.")
	}

	return user.NewSession(), nil
}
开发者ID:francoishill,项目名称:leeroyci,代码行数:30,代码来源:login.go



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang securecookie.CodecsFromPairs函数代码示例发布时间:2022-05-23
下一篇:
Golang json.NewCodec函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap