本文整理汇总了Golang中github.com/gorilla/schema.NewDecoder函数的典型用法代码示例。如果您正苦于以下问题:Golang NewDecoder函数的具体用法?Golang NewDecoder怎么用?Golang NewDecoder使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewDecoder函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
}
示例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)
}
示例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())
}
}
示例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
}
示例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
}
示例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))
}
示例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)
}
示例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)
}
}
}
}
示例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
}
示例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)
}
示例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)
}
}
示例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
}
示例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)
}
}
示例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
}
示例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)
}
}