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) }
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) }
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()) } }
// 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 }
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 }
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)) }
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) }
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) } } } }
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 }
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) }
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) } }
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 }
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) } }
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 }
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) } }
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 }
func init() { Decoder = schema.NewDecoder() RegisterMeatHandlers(route.Router) RegisterUserHandlers(route.Router) http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("resources/static/")))) }
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 }
// 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 }
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 }
func HandleOrganizationCreate(w http.ResponseWriter, r *http.Request) { ctx := GetContext(r) if ctx.Account == nil { http.Redirect(w, r, "/login", http.StatusSeeOther) return } err := r.ParseForm() catch(r, err) body := struct { Name string `schema:"name"` }{} err = schema.NewDecoder().Decode(&body, r.PostForm) catch(r, err) switch { case body.Name == "": RedirectBack(w, r) return } org := data.Organization{ Name: body.Name, OwnerID: ctx.Account.ID, CreatorID: ctx.Account.ID, } err = org.Put() catch(r, err) http.Redirect(w, r, "/organizations/"+org.ID.Hex()+"/projects", http.StatusSeeOther) }
// ServeHTTP implementation. func (c *Client) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { log.Println("invalid " + r.Method + " connection from " + r.RemoteAddr) http.NotFound(w, r) return } msg := IMessage{} err := r.ParseForm() if err != nil { log.Println(err) http.NotFound(w, r) return } defer r.Body.Close() decoder := schema.NewDecoder() err = decoder.Decode(&msg, r.PostForm) if err != nil { log.Println(err) http.NotFound(w, r) return } if msg.Token == "" { log.Println("no token from " + r.RemoteAddr) http.NotFound(w, r) return } if c.Token != "" { if msg.Token != c.Token { log.Println("invalid token " + msg.Token + " from " + r.RemoteAddr) http.NotFound(w, r) return } } c.In <- msg }
func PopulateInterface(document Document, StructType reflect.Type) (reflect.Value, error) { decoder := schema.NewDecoder() decoder.IgnoreUnknownKeys(true) gorillaMap := make(map[string][]string) for key, field := range document.Fields { var fieldString []string switch fieldType := field.(type) { case string: fieldString = []string{fieldType} case bool: fieldString = []string{strconv.FormatBool(fieldType)} case float64: fieldString = []string{strconv.FormatFloat(fieldType, 'f', -1, 64)} } if len(fieldString) > 0 { gorillaMap[key] = fieldString } } documentStruct := reflect.New(StructType) err := decoder.Decode(documentStruct.Interface(), gorillaMap) if err != nil { return reflect.Value{}, err } return documentStruct, nil }
func updatePrinter(writer http.ResponseWriter, request *http.Request) { request.ParseForm() printer := new(data.Printer) decoder := schema.NewDecoder() id := request.FormValue("id") request.Form.Del("id") err := decoder.Decode(printer, request.Form) fmt.Println(request.Form) if check(err, 400, &writer) { return } if printer.Name == "" { log.Println(errors.New("No Name Provided")) http.Error(writer, http.StatusText(400), 400) return } printer.Id, err = uuid.FromString(id) if check(err, 400, &writer) { return } err = printerQueue.Update(*printer, &configImpl) if check(err, 400, &writer) { return } json, err := json.MarshalIndent(printerQueue.Queue, "", " ") if check(err, 500, &writer) { return } writer.Write(json) }
func slashCommandHandler(w http.ResponseWriter, r *http.Request) { err := r.ParseForm() if err != nil { w.WriteHeader(http.StatusBadRequest) return } d := schema.NewDecoder() command := new(robots.SlashCommand) err = d.Decode(command, r.PostForm) if err != nil { log.Println("Couldn't parse post request:", err) } if command.Command == "" || command.Token == "" { log.Printf("[DEBUG] Ignoring request from unidentified source: %s - %s", command.Token, r.Host) w.WriteHeader(http.StatusBadRequest) return } command.Robot = command.Command[1:] if token := os.Getenv(fmt.Sprintf("%s_SLACK_TOKEN", strings.ToUpper(command.Robot))); token != "" && token != command.Token { log.Printf("[DEBUG] Ignoring request from unidentified source: %s - %s", command.Token, r.Host) w.WriteHeader(http.StatusBadRequest) } robots := getRobots(command.Robot) if len(robots) == 0 { plainResp(w, "No robot for that command yet :(") return } resp := "" for _, robot := range robots { resp += fmt.Sprintf("\n%s", robot.Run(&command.Payload)) } plainResp(w, strings.TrimSpace(resp)) }
func nameTagSubmit(writer http.ResponseWriter, request *http.Request) { defer http.Redirect(writer, request, "/manager", 301) log.Println("Name Tags Submited") err := request.ParseForm() if check(err, 500, &writer) { return } if request.MultipartForm != nil && request.MultipartForm.Value != nil { configImpl.DebugLog(request.MultipartForm.Value) } wrapper := new(data.DataWrapper) decoder := schema.NewDecoder() err = decoder.Decode(wrapper, request.PostForm) if err != nil { log.Println("Decoding form data failed:", err) http.Error(writer, http.StatusText(400), 400) return } for i := 0; i < len(wrapper.NameTagQueue.Queue); i++ { if len(wrapper.NameTagQueue.Queue) >= i+1 && wrapper.NameTagQueue.Queue[i].Name != "" { log.Println(wrapper.NameTagQueue.Queue[i].Id) if len(wrapper.Delete) >= i+1 && wrapper.Delete[i] == true { err := nameTagQueue.Remove(wrapper.NameTagQueue.Queue[i].Id, &configImpl) if err != nil { log.Println(err) } } else { nameTagQueue.Queue[i] = wrapper.NameTagQueue.Queue[i] } } } nameTagQueue.Save(&configImpl) fmt.Println("Name Tags written") }
// update updates an existing user based on the form. func (u userAdminForm) update(request *http.Request, uid int64) 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 } user, err := database.GetUserByID(uid) if err != nil { return err } _, err = user.Update( form.Email, form.FirstName, form.LastName, form.Password, form.Admin, ) return err }
func printersSubmit(writer http.ResponseWriter, request *http.Request) { defer http.Redirect(writer, request, "/manager#printersTab", 301) fmt.Println("Printers Submited") err := request.ParseMultipartForm(0) if err != nil { fmt.Println("Parsing form data failed:", err) http.Error(writer, http.StatusText(500), 500) return } if request.MultipartForm != nil && request.MultipartForm.Value != nil { configImpl.DebugLog(request.MultipartForm.Value) } wrapper := new(data.DataWrapper) decoder := schema.NewDecoder() err = decoder.Decode(wrapper, request.MultipartForm.Value) if err != nil { fmt.Println("Decoding form data failed:", err) http.Error(writer, http.StatusText(400), 400) return } // fmt.Printf("%v\n", wrapper.PrinterQueue.Queue) for i := 0; i < len(wrapper.PrinterQueue.Queue); i++ { if len(wrapper.PrinterQueue.Queue) >= i+1 && wrapper.PrinterQueue.Queue[i].Name != "" { if len(wrapper.Delete) >= i+1 && wrapper.Delete[i] == true { printerQueue.Remove(wrapper.PrinterQueue.Queue[i].Id, &configImpl) } else { fmt.Printf("Setting printer: %s to positon: %d\n", wrapper.PrinterQueue.Queue[i].Name, i) fmt.Printf("%v\n", wrapper.PrinterQueue.Queue[i]) printerQueue.Queue[i] = wrapper.PrinterQueue.Queue[i] } } } printerQueue.Save(&configImpl) fmt.Println("Printers written") }
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) } }
func QueryFromValues(u url.Values) (*Query, error) { decoder := schema.NewDecoder() decoder.RegisterConverter(time.Time{}, convertTime) q := new(Query) err := decoder.Decode(q, u) return q, err }