func (p *loginAccountContext) SetFromUrlEncoded(values url.Values) { p.username = values.Get("username") p.password = values.Get("password") p.inputValidated = false p.user = nil p.result = nil }
func intFromQuery(ps url.Values, name string, defaultVal int) (int, error) { s := ps.Get(name) if s == "" { return defaultVal, nil } return strconv.Atoi(s) }
func challengeFromForm(form url.Values) (Challenge, error) { var err error c := Challenge{} fmt.Println(form) c.Title = form.Get("title") if c.Title == "" { return c, errors.New("No Title") } c.Description = template.HTML(form.Get("description")) if c.Title == "" { return c, errors.New("No Description") } c.Alias = form.Get("path") if c.Alias == "" { return c, errors.New("No path") } c.MaxScore, err = strconv.Atoi(form.Get("points")) if err != nil || c.MaxScore <= 0 || c.MaxScore > MaxChallengeScore { return c, errors.New("Wrong Points Format or Missing") } c.Category = form.Get("category") if c.Category == "" { return c, errors.New("No Category") } return c, nil }
//磁盘保存文件 func saveFile(reader io.Reader, query url.Values) error { fileName := query.Get("name") if fileName == "" { return errors.New("name is empty") } if err := ensureDir("static"); err != nil { return err } body, err := ioutil.ReadAll(reader) if err != nil { return err } filePath := path.Join("static", fileName) file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0777) defer file.Close() if err != nil { return err } _, err = file.Write(body) if err != nil { return err } return nil }
func handleFrontendPost(self *dialogNode, form url.Values, conf *configparser.Configuration) (*dialogNode, error) { if form.Get("back") == "true" { return self.parent, nil } var next *dialogNode sect, _ := conf.Section("frontend") name := form.Get("name") locale := form.Get("locale") allow_files := form.Get("allow_files") if allow_files != "1" { allow_files = "0" } json_api := form.Get("json") if json_api != "1" { json_api = "0" next = self.children["next"] } else { next = self.children["json"] } sect.Add("name", name) sect.Add("locale", locale) sect.Add("allow_files", allow_files) sect.Add("json-api", json_api) err := checkLocale(locale) if err != nil { return self, err } return next, nil }
// Dispatch inspects the "command" parameter and dispatches the request to the // appropriate handler function. func Dispatch(params url.Values) (response JSONResponse) { switch params.Get("command") { case "fetch-meal-list": return fetchMealList(params) case "toggle-favourite": return toggleFavourite(params) case "delete-meal": return deleteMeal(params) case "fetch-all-tags": return fetchAllTags(params) case "fetch-servings": return fetchServings(params) case "fetch-suggestions": return fetchSuggestions(params) case "update-serving": return updateServing(params) case "delete-serving": return deleteServing(params) case "update-notes": return updateNotes(params) case "fetch-meal-plans": return fetchMealPlans(params) } return JSONResponse{Error: "Invalid or missing command"} }
// Update 更新用户信息 func (self UserLogic) Update(ctx context.Context, me *model.Me, form url.Values) (errMsg string, err error) { objLog := GetLogger(ctx) if form.Get("open") != "1" { form.Set("open", "0") } user := &model.User{} err = schemaDecoder.Decode(user, form) if err != nil { objLog.Errorln("userlogic update, schema decode error:", err) errMsg = "服务内部错误" return } cols := "name,open,city,company,github,weibo,website,monlog,introduce" // 变更了邮箱 if user.Email != me.Email { cols += ",email,status" user.Status = model.UserStatusNoAudit } _, err = MasterDB.Id(me.Uid).Cols(cols).Update(user) if err != nil { objLog.Errorf("更新用户 【%d】 信息失败:%s", me.Uid, err) errMsg = "对不起,服务器内部错误,请稍后再试!" return } // 修改用户资料,活跃度+1 go self.IncrUserWeight("uid", me.Uid, 1) return }
// Modify 修改主题 // user 修改人的(有可能是作者或管理员) func (TopicLogic) Modify(ctx context.Context, user *model.Me, form url.Values) (errMsg string, err error) { objLog := GetLogger(ctx) change := map[string]interface{}{ "editor_uid": user.Uid, } fields := []string{"title", "content", "nid"} for _, field := range fields { change[field] = form.Get(field) } tid := form.Get("tid") _, err = MasterDB.Table(new(model.Topic)).Id(tid).Update(change) if err != nil { objLog.Errorf("更新主题 【%s】 信息失败:%s\n", tid, err) errMsg = "对不起,服务器内部错误,请稍后再试!" return } // 修改主题,活跃度+2 go DefaultUser.IncrUserWeight("uid", user.Uid, 2) return }
func verifySign(c Config, u url.Values) (err error) { p := kvpairs{} sign := "" for k := range u { v := u.Get(k) switch k { case "sign": sign = v continue case "sign_type": continue } p = append(p, kvpair{k, v}) } if sign == "" { err = fmt.Errorf("sign not found") return } p = p.RemoveEmpty() p.Sort() fmt.Println(u) if md5Sign(p.Join(), c.Key) != sign { err = fmt.Errorf("sign invalid") return } return }
func parseInt(vals url.Values, v string, def, min, max int) int { rv, err := strconv.ParseInt(vals.Get(v), 10, 32) if err != nil || int(rv) < min || int(rv) > max { return def } return int(rv) }
func testUpdatePost(t *testing.T, title string, markdown string) { // create JSON payload var p Post p.Title = title p.Markdown = markdown p.Content = string(blackfriday.MarkdownCommon([]byte(markdown))) apiPayload, _ := json.Marshal(p) // save changes to global object for further testing comparison post.Title = p.Title post.Content = string(blackfriday.MarkdownCommon([]byte(markdown))) post.Markdown = markdown post.Excerpt = excerpt.Make(p.Content, 15) testUpdatePostAPI(t, apiPayload) // creates form-encoded payload p2 := url.Values{} p2.Set("title", title) p2.Add("markdown", markdown) frontendPayload := p2.Encode() // save changes to global object for further testing comparison post.Title = p2.Get("title") post.Markdown = p2.Get("markdown") post.Excerpt = excerpt.Make(post.Content, 15) testUpdatePostFrontend(t, frontendPayload) TestReadPost(t) }
// ParseURL parses s into a ConnectionURL struct. func ParseURL(s string) (conn ConnectionURL, err error) { var u *url.URL if strings.HasPrefix(s, connectionScheme+"://") == false { return conn, fmt.Errorf(`Expecting file:// connection scheme.`) } if u, err = url.Parse(s); err != nil { return conn, err } conn.Database = u.Host + u.Path conn.Options = map[string]string{} var vv url.Values if vv, err = url.ParseQuery(u.RawQuery); err != nil { return conn, err } for k := range vv { conn.Options[k] = vv.Get(k) } return conn, err }
// New creates the HTML for a select menu instance with the specified parameters. func New(options []string, defaultOption string, query url.Values, queryParameter string) template.HTML { selectElement := &html.Node{Type: html.ElementNode, Data: "select"} var selectedOption = defaultOption if query.Get(queryParameter) != "" { selectedOption = query.Get(queryParameter) } if !contains(options, selectedOption) { options = append(options, selectedOption) } for _, option := range options { o := &html.Node{Type: html.ElementNode, Data: "option"} o.AppendChild(htmlg.Text(option)) if option == selectedOption { o.Attr = append(o.Attr, html.Attribute{Key: "selected"}) } selectElement.AppendChild(o) } selectElement.Attr = append(selectElement.Attr, html.Attribute{ Key: "oninput", // HACK: Don't use Sprintf, properly encode (as json at this time). Val: fmt.Sprintf(`SelectMenuOnInput(event, this, %q, %q);`, strconv.Quote(defaultOption), strconv.Quote(queryParameter)), }) return htmlg.Render(selectElement) }
// fetchMealPlans handles an API call to return a list of meal plans that // overlap with a specified inclusive date range. Expected parameters: from, to. // Returns: an array of meal plan objects. func fetchMealPlans(params url.Values) (response JSONResponse) { from, err := time.Parse(mpdata.JSONDateFormat, params.Get("from")) if err != nil { return JSONResponse{Error: "Invalid or missing 'from' parameter"} } to, err := time.Parse(mpdata.JSONDateFormat, params.Get("to")) if err != nil { return JSONResponse{Error: "Invalid or missing 'to' parameter"} } var mps []*mpdata.MealPlan err = mpdb.WithConnection(func(db *sql.DB) (err error) { return mpdb.WithTransaction(db, func(tx *sql.Tx) (err error) { mps, err = mpdb.ListMealPlansBetween(tx, from, to) return err }) }) if err != nil { log.Printf("Database error: %s\n", err.Error()) return JSONResponse{Error: "Database error"} } return JSONResponse{Success: mps} }
func Test_client_buildWriteFileRequest(t *testing.T) { c := client{ options: ClientOptions{ Locale: "init__locale", Root: "init__root", Token: "init__token", }} var f bytes.Buffer p := url.Values{} p.Set("locale", "callers__locale") r, e := c.buildWriteFileRequest("somepath", &f, 100, p) assert.NoError(t, e) assert.Equal(t, r.Method, "PUT") auth := r.Header.Get("Authorization") assert.Contains(t, auth, "Bearer") assert.Contains(t, auth, "init__token") clen := r.Header.Get("Content-Length") assert.Equal(t, clen, "100") u := r.URL assert.Equal(t, u.Scheme, "https") assert.Equal(t, u.Host, "api-content.dropbox.com") assert.Equal(t, u.Path, "/1/files_put/init__root/somepath") p = u.Query() assert.Equal(t, p.Get("locale"), "callers__locale") assert.Equal(t, len(p), 1) }
func (oat *OAuthToken) HeaderValue(method string, fullUrl string, query url.Values, form url.Values) string { var pairs = url.Values{} nonce := make([]byte, 32) io.ReadFull(rand.Reader, nonce) timestamp := fmt.Sprintf("%d", time.Now().Unix()) if query != nil { for k, _ := range query { pairs.Set(k, query.Get(k)) } } if form != nil { for k, _ := range form { pairs.Set(k, form.Get(k)) } } pairs.Set("oauth_consumer_key", oat.ConsumerKey) pairs.Set("oauth_nonce", string(nonce)) pairs.Set("oauth_signature_method", OAUTH_SIGNATURE_METHOD) pairs.Set("oauth_timestamp", timestamp) pairs.Set("oauth_token", oat.Token) pairs.Set("oauth_version", OAUTH_VERSION) signature := oat.createSignature(method, fullUrl, pairs) return fmt.Sprintf( OAUTH_AUTH_HEADER, percentEncode(oat.ConsumerKey), percentEncode(string(nonce)), percentEncode(signature), OAUTH_SIGNATURE_METHOD, timestamp, percentEncode(oat.Token), OAUTH_VERSION, ) }
func (ph *patHandler) Path(values ...url.Values) string { // TODO refactor to build string in place or from preprocessed parts // find captures var i int captures := make([]string, 0) for i < len(ph.pat) { switch { default: i++ case ph.pat[i] == ':': var name string name, _, i = match(ph.pat, isAlnum, i+1) captures = append(captures, name) } } // setup url values v := url.Values{} if len(values) > 0 { v = values[0] } path := ph.pat for _, capture := range captures { first := v.Get(capture) path = strings.Replace(path, ":"+capture, first, -1) v.Del(capture) } if query := v.Encode(); len(query) > 0 { path += strings.Join([]string{"?", query}, "") } return path }
func getFloat64(q url.Values, key string, d float64) float64 { f, err := strconv.ParseFloat(q.Get(key), 64) if err != nil { return d } return f }
func (p *ProviderData) Redeem(redirectURL, code string) (s *SessionState, err error) { if code == "" { err = errors.New("missing code") return } params := url.Values{} params.Add("redirect_uri", redirectURL) params.Add("client_id", p.ClientID) params.Add("client_secret", p.ClientSecret) params.Add("code", code) params.Add("grant_type", "authorization_code") var req *http.Request req, err = http.NewRequest("POST", p.RedeemURL.String(), bytes.NewBufferString(params.Encode())) if err != nil { return } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") var resp *http.Response resp, err = http.DefaultClient.Do(req) if err != nil { return nil, err } var body []byte body, err = ioutil.ReadAll(resp.Body) resp.Body.Close() if err != nil { return } if resp.StatusCode != 200 { err = fmt.Errorf("got %d from %q %s", resp.StatusCode, p.RedeemURL.String(), body) return } // blindly try json and x-www-form-urlencoded var jsonResponse struct { AccessToken string `json:"access_token"` } err = json.Unmarshal(body, &jsonResponse) if err == nil { s = &SessionState{ AccessToken: jsonResponse.AccessToken, } return } var v url.Values v, err = url.ParseQuery(string(body)) if err != nil { return } if a := v.Get("access_token"); a != "" { s = &SessionState{AccessToken: a} } else { err = fmt.Errorf("no access token found %s", body) } return }
func ValidateMetricParams(queries url.Values) []ErrorResponse { var errs []ErrorResponse if queries["exec_time"] == nil { errs = append(errs, ErrorResponse{ Message: "exec_time not set", Code: fmt.Sprintf("%d", http.StatusBadRequest), Details: fmt.Sprintf("Please use exec_time url parameter in zulu format (like %s) to indicate the exact probe execution time", zuluForm), }) } else { execDate := queries.Get("exec_time") errExec := validateDate(execDate) if errExec != nil { errs = append(errs, ErrorResponse{ Message: "exec_time parsing error", Code: fmt.Sprintf("%d", http.StatusBadRequest), Details: fmt.Sprintf("Error parsing date string %s please use zulu format like %s", execDate, zuluForm), }) } } return errs }
// parseControlInfo builds ControlInfo from url.Values. func parseControlInfo(values url.Values) *ControlInfo { mode := values.Get("mode") pow := values.Get("pow") if mode == "" || pow == "" { return nil } info := &ControlInfo{Power: (pow == "1")} info.token, _ = strconv.Atoi(values.Get("shum")) info.User = (info.token == tokenNoControl) stemp, err := strconv.ParseFloat(values.Get("stemp"), 64) if err == nil { info.SetPoint = &stemp } m := ModeOther switch values.Get("mode") { case "0", "1", "7": m = ModeAuto case "3": m = ModeCool case "4": m = ModeHeat } info.Mode = m return info }
// NewKey creates a new OTP key. // keyType must be either TypeTotp or TypeHotp. // label is required. keyLen <= 0, defaults to 10. // algorithm == "", defaults to "sha1". // digits <= 0, defaults to 6 func NewKey(keyType string, keyLen int, label, issuer, algorithm string, digits int, extraParams url.Values) (Key, error) { switch keyType { case TypeTotp: // TOTP // parse period parameter p := extraParams.Get("period") var ( err error pp int ) if p != "" { pp, err = strconv.Atoi(p) if err != nil { return nil, &Error{ECInvalidPeriod, fmt.Sprintf("invalid period: %v", p), err} } else if pp == 0 { pp = DefaultPeriod } } return NewTotp(keyLen, label, issuer, algorithm, digits, pp) case TypeHotp: // HOTP // check for counter parameter c := extraParams.Get("counter") if c == "" { return nil, &Error{ECMissingCounter, "counter parameter is missing", nil} } cc, err := strconv.Atoi(c) if err != nil { return nil, &Error{ECInvalidCounter, fmt.Sprintf("bad counter: %v", c), err} } return NewHotp(keyLen, label, issuer, algorithm, digits, cc) default: return nil, &Error{ECInvalidOtpType, fmt.Sprintf("invalid OTP authentication type: %v", keyType), nil} } }
func (srv *Server) makeHealthCheck(value url.Values) elb.HealthCheck { ht := 10 timeout := 5 ut := 2 interval := 30 target := "TCP:80" if v := value.Get("HealthCheck.HealthyThreshold"); v != "" { ht, _ = strconv.Atoi(v) } if v := value.Get("HealthCheck.Timeout"); v != "" { timeout, _ = strconv.Atoi(v) } if v := value.Get("HealthCheck.UnhealthyThreshold"); v != "" { ut, _ = strconv.Atoi(v) } if v := value.Get("HealthCheck.Interval"); v != "" { interval, _ = strconv.Atoi(v) } if v := value.Get("HealthCheck.Target"); v != "" { target = v } return elb.HealthCheck{ HealthyThreshold: ht, Interval: interval, Target: target, Timeout: timeout, UnhealthyThreshold: ut, } }
func (tm *TaskManager) NewTask(s *Store, args url.Values) (tid string, e error) { tm.lock.Lock() defer tm.lock.Unlock() tt := args.Get("task") vid := args.Get("volume") tid = tt + "-" + vid if _, ok := tm.taskList[tid]; ok { return tid, ErrTaskExists } var tw TaskWorker switch tt { case TaskVacuum: tw, e = NewVacuumTask(s, args) case TaskReplicate: tw, e = NewReplicaTask(s, args) case TaskBalance: } if e != nil { return } if tw == nil { return "", ErrTaskInvalid } tm.taskList[tid] = newTask(tw, tid) return tid, nil }
// queryBool returns the query parameter parsed as a boolean. An empty value // ("?foo") is considered true, as is any value string except false // ("?foo=false"). func queryBool(q url.Values, key string) bool { if _, ok := q[key]; !ok { return false } return q.Get(key) != "false" }
func buildAuthHeader(vals url.Values) string { var buf bytes.Buffer if _, ok := vals["oauth_version"]; !ok { vals.Set("oauth_version", "1.0") } fmt.Fprintf(&buf, "OAuth") remove := []string{} for k := range vals { if !strings.HasPrefix(k, "oauth_") { continue } remove = append(remove, k) } sort.Strings(remove) for n, k := range remove { if n > 0 { buf.WriteByte(',') } v := vals.Get(k) if k == "oauth_signature" { v = url.QueryEscape(v) } fmt.Fprintf(&buf, " %s=%q", k, v) delete(vals, k) } return buf.String() }
func (k *Kraken) SendAuthenticatedHTTPRequest(method string, values url.Values) (interface{}, error) { path := fmt.Sprintf("/%s/private/%s", KRAKEN_API_VERSION, method) values.Set("nonce", strconv.FormatInt(time.Now().UnixNano(), 10)) secret, err := Base64Decode(k.APISecret) if err != nil { return nil, err } shasum := GetSHA256([]byte(values.Get("nonce") + values.Encode())) signature := Base64Encode(GetHMAC(HASH_SHA512, append([]byte(path), shasum...), secret)) if k.Verbose { log.Printf("Sending POST request to %s, path: %s.", KRAKEN_API_URL, path) } headers := make(map[string]string) headers["API-Key"] = k.ClientKey headers["API-Sign"] = signature resp, err := SendHTTPRequest("POST", KRAKEN_API_URL+path, headers, strings.NewReader(values.Encode())) if err != nil { return nil, err } if k.Verbose { log.Printf("Recieved raw: \n%s\n", resp) } return resp, nil }
func hc(values url.Values) { var color, message string switch values.Get("Status") { case "Up": color = getColor(config.UpColor) message = formatMessage(values, config.MessageUp) case "Down": color = getColor(config.DownColor) message = formatMessage(values, config.MessageDown) } c := hipchat.Client{AuthToken: config.AuthToken} req := hipchat.MessageRequest{ RoomId: config.RoomId, From: config.From, Message: message, Color: color, MessageFormat: hipchat.FormatText, Notify: config.Notify, } if err := c.PostMessage(req); err != nil { fmt.Println("Expected no error, but got %q", err) } }
func ParseAuthCodeRequest(q url.Values) (AuthCodeRequest, error) { acr := AuthCodeRequest{ ResponseType: q.Get("response_type"), ClientID: q.Get("client_id"), State: q.Get("state"), Scope: make([]string, 0), } qs := strings.TrimSpace(q.Get("scope")) if qs != "" { acr.Scope = strings.Split(qs, " ") } err := func() error { if acr.ClientID == "" { return NewError(ErrorInvalidRequest) } redirectURL := q.Get("redirect_uri") if redirectURL != "" { ru, err := url.Parse(redirectURL) if err != nil { return NewError(ErrorInvalidRequest) } acr.RedirectURL = ru } return nil }() return acr, err }
func parseStr(values url.Values, key, defaultValue string) (string, bool) { value := values.Get(key) if value == "" { return defaultValue, false } return value, true }