本文整理汇总了Golang中url.ParseQuery函数的典型用法代码示例。如果您正苦于以下问题:Golang ParseQuery函数的具体用法?Golang ParseQuery怎么用?Golang ParseQuery使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ParseQuery函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ParseForm
// ParseForm parses the raw query from the URL.
//
// For POST or PUT requests, it also parses the request body as a form.
// If the request Body's size has not already been limited by MaxBytesReader,
// the size is capped at 10MB.
//
// ParseMultipartForm calls ParseForm automatically.
// It is idempotent.
func (r *Request) ParseForm() (err os.Error) {
if r.Form != nil {
return
}
if r.URL != nil {
r.Form, err = url.ParseQuery(r.URL.RawQuery)
}
if r.Method == "POST" || r.Method == "PUT" {
if r.Body == nil {
return os.NewError("missing form body")
}
ct := r.Header.Get("Content-Type")
ct, _, err := mime.ParseMediaType(ct)
switch {
case ct == "text/plain" || ct == "application/x-www-form-urlencoded" || ct == "":
var reader io.Reader = r.Body
maxFormSize := int64(1<<63 - 1)
if _, ok := r.Body.(*maxBytesReader); !ok {
maxFormSize = int64(10 << 20) // 10 MB is a lot of text.
reader = io.LimitReader(r.Body, maxFormSize+1)
}
b, e := ioutil.ReadAll(reader)
if e != nil {
if err == nil {
err = e
}
break
}
if int64(len(b)) > maxFormSize {
return os.NewError("http: POST too large")
}
var newValues url.Values
newValues, e = url.ParseQuery(string(b))
if err == nil {
err = e
}
if r.Form == nil {
r.Form = make(url.Values)
}
// Copy values into r.Form. TODO: make this smoother.
for k, vs := range newValues {
for _, value := range vs {
r.Form.Add(k, value)
}
}
case ct == "multipart/form-data":
// handled by ParseMultipartForm (which is calling us, or should be)
// TODO(bradfitz): there are too many possible
// orders to call too many functions here.
// Clean this up and write more tests.
// request_test.go contains the start of this,
// in TestRequestMultipartCallOrder.
default:
return &badStringError{"unknown Content-Type", ct}
}
}
return err
}
示例2: ParseForm
// ParseForm parses the raw query.
// For POST requests, it also parses the request body as a form.
// ParseMultipartForm calls ParseForm automatically.
// It is idempotent.
func (r *Request) ParseForm() (err os.Error) {
if r.Form != nil {
return
}
if r.URL != nil {
r.Form, err = url.ParseQuery(r.URL.RawQuery)
}
if r.Method == "POST" {
if r.Body == nil {
return os.NewError("missing form body")
}
ct := r.Header.Get("Content-Type")
switch strings.SplitN(ct, ";", 2)[0] {
case "text/plain", "application/x-www-form-urlencoded", "":
const maxFormSize = int64(10 << 20) // 10 MB is a lot of text.
b, e := ioutil.ReadAll(io.LimitReader(r.Body, maxFormSize+1))
if e != nil {
if err == nil {
err = e
}
break
}
if int64(len(b)) > maxFormSize {
return os.NewError("http: POST too large")
}
var newValues url.Values
newValues, e = url.ParseQuery(string(b))
if err == nil {
err = e
}
if r.Form == nil {
r.Form = make(url.Values)
}
// Copy values into r.Form. TODO: make this smoother.
for k, vs := range newValues {
for _, value := range vs {
r.Form.Add(k, value)
}
}
case "multipart/form-data":
// handled by ParseMultipartForm
default:
return &badStringError{"unknown Content-Type", ct}
}
}
return err
}
示例3: TestParseForm
func TestParseForm(t *testing.T) {
for i, test := range parseTests {
form, err := url.ParseQuery(test.query)
if err != nil {
t.Errorf("test %d: Unexpected error: %v", i, err)
continue
}
if len(form) != len(test.out) {
t.Errorf("test %d: len(form) = %d, want %d", i, len(form), len(test.out))
}
for k, evs := range test.out {
vs, ok := form[k]
if !ok {
t.Errorf("test %d: Missing key %q", i, k)
continue
}
if len(vs) != len(evs) {
t.Errorf("test %d: len(form[%q]) = %d, want %d", i, k, len(vs), len(evs))
continue
}
for j, ev := range evs {
if v := vs[j]; v != ev {
t.Errorf("test %d: form[%q][%d] = %q, want %q", i, k, j, v, ev)
}
}
}
}
}
示例4: handle
func handle(w http.ResponseWriter, r *http.Request) {
params, err := url.ParseQuery(r.URL.RawQuery)
check(err)
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add(
"Access-Control-Allow-Methods",
"OPTIONS, HEAD, GET, POST, PUT, DELETE",
)
switch r.Method {
case "OPTIONS":
case "HEAD":
case "GET":
get(w, r)
case "POST":
if len(params["_method"]) > 0 && params["_method"][0] == "DELETE" {
delete(w, r)
} else {
post(w, r)
}
case "DELETE":
delete(w, r)
default:
http.Error(w, "501 Not Implemented", http.StatusNotImplemented)
}
}
示例5: Canonicalize
// Generates the canonical string-to-sign for dsocial services.
// You shouldn't need to use this directly.
func (p *signer) Canonicalize(req *http.Request) (out string, err os.Error) {
fv, err := url.ParseQuery(req.URL.RawQuery)
if err == nil {
out = strings.Join([]string{req.Method, req.Host, req.URL.Path, SortedEscape(fv)}, "\n")
}
return
}
示例6: UpdateLocation
func UpdateLocation(w http.ResponseWriter, r *http.Request, validator auth.Validator, manager chan ManagerRequest) {
auth_ok, client := validator.Validate(w, r)
if !auth_ok {
return
}
params, _ := url.ParseQuery(r.URL.RawQuery)
location, err := ParseLocationFromRequest(params)
if err != nil {
http.Error(w, *err, http.StatusBadRequest)
return
}
log.Printf("Got update request for %s with timestamp %d", *client, location.timestamp)
// Reject timestamp from future.
now := time.Seconds() * 1000
if location.timestamp > now {
location.timestamp = now
}
out := make(chan bool, 1)
updateRequest := &UpdateLocationRequest{*client, location, out}
manager <- updateRequest
_ = <-out
response := "ok"
fmt.Fprintf(w, response)
}
示例7: camliMode
func camliMode(req *http.Request) string {
// TODO-GO: this is too hard to get at the GET Query args on a
// POST request.
m, err := url.ParseQuery(req.URL.RawQuery)
if err != nil {
return ""
}
if mode, ok := m["camli.mode"]; ok && len(mode) > 0 {
return mode[0]
}
return ""
}
示例8: GetAccessToken
func (o *OAuthClient) GetAccessToken(requestToken *RequestToken, OAuthVerifier string) (*AccessToken, os.Error) {
if requestToken == nil || requestToken.OAuthToken == "" || requestToken.OAuthTokenSecret == "" {
return nil, os.NewError("Invalid Request token")
}
nonce := getNonce(40)
params := map[string]string{
"oauth_nonce": nonce,
"oauth_token": requestToken.OAuthToken,
"oauth_verifier": OAuthVerifier,
"oauth_signature_method": "HMAC-SHA1",
"oauth_timestamp": strconv.Itoa64(time.Seconds()),
"oauth_consumer_key": o.ConsumerKey,
"oauth_version": "1.0",
}
base := signatureBase("POST", requestTokenUrl.Raw, params)
signature := signRequest(base, o.ConsumerSecret, requestToken.OAuthTokenSecret)
params["oauth_signature"] = URLEscape(signature)
authBuf := bytes.NewBufferString("OAuth ")
i := 0
for k, v := range params {
authBuf.WriteString(fmt.Sprintf("%s=%q", k, v))
if i < len(params)-1 {
authBuf.WriteString(", ")
}
i++
}
request := httplib.Post(accessTokenUrl.Raw)
request.Header("Authorization", authBuf.String())
request.Body("")
resp, err := request.AsString()
tokens, err := url.ParseQuery(resp)
if err != nil {
return nil, err
}
at := AccessToken{
OAuthTokenSecret: tokens["oauth_token_secret"][0],
OAuthToken: tokens["oauth_token"][0],
UserId: tokens["user_id"][0],
ScreenName: tokens["screen_name"][0],
}
return &at, nil
}
示例9: parseAccessToken
// Given the returned response from the access token request, pull out the
// access token and token secret. Store a copy of any other values returned,
// too, since some services (like Twitter) return handy information such
// as the username.
func (c *UserConfig) parseAccessToken(response *http.Response) os.Error {
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
params, err := url.ParseQuery(string(body))
tokenKey := params.Get("oauth_token")
tokenSecret := params.Get("oauth_token_secret")
if tokenKey == "" || tokenSecret == "" {
return os.NewError("No token or secret found")
}
c.AccessTokenKey = tokenKey
c.AccessTokenSecret = tokenSecret
c.AccessValues = params
return nil
}
示例10: Poll
func Poll(w http.ResponseWriter, r *http.Request, validator auth.Validator, manager chan ManagerRequest) {
auth_ok, client := validator.Validate(w, r)
if !auth_ok {
return
}
params, _ := url.ParseQuery(r.URL.RawQuery)
outFormat, err := query.GetQueryParam(params, "output")
if err != nil {
jsonFormat := "json"
outFormat = &jsonFormat
}
timeout, err := query.GetInt32QueryParam(params, "timeout")
if err != nil {
timeout = kDefaultPollTimeoutSec
}
if timeout <= 0 || timeout > 60*60 {
http.Error(w, fmt.Sprintf("Invalid timeout: %d", timeout), http.StatusBadRequest)
return
}
log.Printf("Got poll request from %s with timeout %d", *client, timeout)
out := make(chan *map[string]Location, 1)
manager <- &WaitForUpdatesRequest{out}
timeoutChan := make(chan bool, 1)
go func() {
time.Sleep(int64(timeout) * 1e9)
timeoutChan <- true
}()
select {
case locations := <-out:
log.Printf("Sending update on poll request from %s", *client)
if *outFormat == "proto" {
w.Header().Add("Content-type", "application/octet-stream")
w.Write(PrintLocationsAsProto(*locations))
} else {
w.Write([]byte(PrintLocationsAsJson(*locations)))
}
case <-timeoutChan:
log.Printf("Poll request from %s timed out", *client)
http.Error(w, "Poll request timed out, please try again", http.StatusRequestTimeout)
}
}
示例11: GetLocations
func GetLocations(w http.ResponseWriter, r *http.Request, validator auth.Validator, manager chan ManagerRequest) {
auth_ok, client := validator.Validate(w, r)
if !auth_ok {
return
}
log.Printf("Got locations request from %s", *client)
params, _ := url.ParseQuery(r.URL.RawQuery)
outFormat, err := query.GetQueryParam(params, "output")
locations := GetAllLocations(manager)
if err == nil && *outFormat == "proto" {
w.Header().Add("Content-type", "application/octet-stream")
w.Write(PrintLocationsAsProto(*locations))
} else {
w.Write([]byte(PrintLocationsAsJson(*locations)))
}
}
示例12: handleUploads
func handleUploads(r *http.Request) (fileInfos []*FileInfo) {
fileInfos = make([]*FileInfo, 0)
mr, err := r.MultipartReader()
check(err)
r.Form, err = url.ParseQuery(r.URL.RawQuery)
check(err)
part, err := mr.NextPart()
for err == nil {
if name := part.FormName(); name != "" {
if part.FileName() != "" {
fileInfos = append(fileInfos, handleUpload(r, part))
} else {
r.Form[name] = append(r.Form[name], getFormValue(part))
}
}
part, err = mr.NextPart()
}
return
}
示例13: parseRequestToken
// Given the returned response from a Request token request, parse out the
// appropriate request token and secret fields.
func (c *UserConfig) parseRequestToken(response *http.Response) os.Error {
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
params, err := url.ParseQuery(string(body))
tokenKey := params.Get("oauth_token")
tokenSecret := params.Get("oauth_token_secret")
if tokenKey == "" || tokenSecret == "" {
return os.NewError("No token or secret found")
}
c.RequestTokenKey = tokenKey
c.RequestTokenSecret = tokenSecret
if params.Get("oauth_callback_confirmed") == "false" {
return os.NewError("OAuth callback not confirmed")
}
return nil
}
示例14: JavascriptHandler
func JavascriptHandler(w http.ResponseWriter, r *http.Request) {
params, _ := url.ParseQuery(r.URL.RawQuery)
name, err := query.GetQueryParam(params, "name")
if err != nil {
http.Error(w, *err, http.StatusBadRequest)
return
}
reg := regexp.MustCompile("[^a-z_]")
if reg.MatchString(*name) {
http.Error(w, "Bad filename", http.StatusBadRequest)
return
}
data, osErr := ioutil.ReadFile(*name + ".js")
if osErr != nil {
http.Error(w, "File not found", http.StatusBadRequest)
return
}
w.Header().Add("Content-type", "text/javascript")
w.Write(data)
}
示例15: GetRequestToken
func (o *OAuthClient) GetRequestToken(callback string) *RequestToken {
nonce := getNonce(40)
params := map[string]string{
"oauth_nonce": nonce,
"oauth_callback": URLEscape(callback),
"oauth_signature_method": "HMAC-SHA1",
"oauth_timestamp": strconv.Itoa64(time.Seconds()),
"oauth_consumer_key": o.ConsumerKey,
"oauth_version": "1.0",
}
base := signatureBase("POST", requestTokenUrl.Raw, params)
signature := signRequest(base, o.ConsumerSecret, "")
params["oauth_signature"] = URLEscape(signature)
authBuf := bytes.NewBufferString("OAuth ")
i := 0
for k, v := range params {
authBuf.WriteString(fmt.Sprintf("%s=%q", k, v))
if i < len(params)-1 {
authBuf.WriteString(", ")
}
i++
}
request := httplib.Post(requestTokenUrl.Raw)
request.Header("Authorization", authBuf.String())
request.Body("")
resp, err := request.AsString()
tokens, err := url.ParseQuery(resp)
if err != nil {
println(err.String())
}
confirmed, _ := strconv.Atob(tokens["oauth_callback_confirmed"][0])
rt := RequestToken{
OAuthTokenSecret: tokens["oauth_token_secret"][0],
OAuthToken: tokens["oauth_token"][0],
OAuthCallbackConfirmed: confirmed,
}
return &rt
}