Beispiel #1
0
// BuildImage builds an image from a tarball's url or a Dockerfile in the input
// stream.
//
// See https://goo.gl/xySxCe for more details.
func (c *Client) BuildImage(opts BuildImageOptions) error {
	if opts.OutputStream == nil {
		return ErrMissingOutputStream
	}
	headers, err := headersWithAuth(opts.Auth, c.versionedAuthConfigs(opts.AuthConfigs))
	if err != nil {
		return err
	}

	if opts.Remote != "" && opts.Name == "" {
		opts.Name = opts.Remote
	}
	if opts.InputStream != nil || opts.ContextDir != "" {
		headers["Content-Type"] = "application/tar"
	} else if opts.Remote == "" {
		return ErrMissingRepo
	}
	if opts.ContextDir != "" {
		if opts.InputStream != nil {
			return ErrMultipleContexts
		}
		var err error
		if opts.InputStream, err = createTarStream(opts.ContextDir, opts.Dockerfile); err != nil {
			return err
		}
	}

	qs := queryString(&opts)
	if len(opts.Ulimits) > 0 {
		if b, err := json.Marshal(opts.Ulimits); err == nil {
			item := url.Values(map[string][]string{})
			item.Add("ulimits", string(b))
			qs = fmt.Sprintf("%s&%s", qs, item.Encode())
		}
	}

	if len(opts.BuildArgs) > 0 {
		v := make(map[string]string)
		for _, arg := range opts.BuildArgs {
			v[arg.Name] = arg.Value
		}
		if b, err := json.Marshal(v); err == nil {
			item := url.Values(map[string][]string{})
			item.Add("buildargs", string(b))
			qs = fmt.Sprintf("%s&%s", qs, item.Encode())
		}
	}

	return c.stream("POST", fmt.Sprintf("/build?%s", qs), streamOptions{
		setRawTerminal:    true,
		rawJSONStream:     opts.RawJSONStream,
		headers:           headers,
		in:                opts.InputStream,
		stdout:            opts.OutputStream,
		inactivityTimeout: opts.InactivityTimeout,
		context:           opts.Context,
	})
}
func auth(w http.ResponseWriter, r *http.Request) {
	//form the query with the oauth paramters of our client application
	query := url.Values(map[string][]string{
		"response_type": []string{"code"},
		"client_id":     []string{clientId},
		"redirect_uri":  []string{redirect},
	})
	target, _ := authUrl.Parse(authPath)
	target.RawQuery = url.Values(query).Encode()
	//redirect the user to the auth server
	log.Printf("redirecting user agent to %v", target)
	http.Redirect(w, r, target.String(), http.StatusFound)
}
Beispiel #3
0
func (oa optionalArgs) SetIntArray(k string, ia []int) {
	switch n := len(ia); {
	case n == 0:
		return
	case n == 1:
		url.Values(oa).Set(k, strconv.Itoa(ia[0]))
	default:
		strIds := make([]string, n)
		for i, v := range ia {
			strIds[i] = strconv.Itoa(v)
		}
		url.Values(oa).Set("ids", strings.Join(strIds, ","))
	}
}
Beispiel #4
0
func (oa optionalArgs) SetIdArray(k string, ia []Id) {
	switch n := len(ia); {
	case n == 0:
		return
	case n == 1:
		url.Values(oa).Set(k, strconv.FormatUint(uint64(ia[0]), 10))
	default:
		strIds := make([]string, n)
		for i, v := range ia {
			strIds[i] = strconv.FormatUint(uint64(v), 10)
		}
		url.Values(oa).Set("ids", strings.Join(strIds, ","))
	}
}
Beispiel #5
0
/* getToken gets the authentication token for the given username and
password */
func getToken(u, p string) (string, error) {
	/* Send the request */
	res, err := http.PostForm(authURL, url.Values(map[string][]string{
		"email":    {u},
		"password": {p},
	}))
	if nil != err {
		return "", err
	}
	defer res.Body.Close()
	/* Read body into buffer */
	buf := &bytes.Buffer{}
	_, err = io.Copy(buf, res.Body)
	if nil != err {
		return "", err
	}
	/* If we're not authorized, :( */
	if "Unauthorized" == buf.String() {
		return "", fmt.Errorf("unauthorized")
	}
	/* Struct into which to decode token */
	rs := struct {
		Ok    int
		Token string
	}{}
	/* Unmarshal the JSON */
	if err := json.Unmarshal(buf.Bytes(), &rs); nil != err {
		return "", err
	}

	return rs.Token, nil
}
Beispiel #6
0
func (q Query) CreateAuthenticationRequest(Realm, ReturnTo string) string {
	claimedID := q.ClaimedID
	if claimedID == "" {
		claimedID = "http://specs.openid.net/auth/2.0/identifier_select"
	}
	p := map[string][]string{
		"openid.ns":            []string{"http://specs.openid.net/auth/2.0"},
		"openid.mode":          []string{"checkid_setup"},
		"openid.return_to":     []string{Realm + ReturnTo},
		"openid.realm":         []string{Realm},
		"openid.claimed_id":    []string{claimedID},
		"openid.identity":      []string{claimedID},
		"openid.ns.ax":         []string{"http://openid.net/srv/ax/1.0"},
		"openid.ax.mode":       []string{"fetch_request"},
		"openid.ax.required":   []string{"email"},
		"openid.ax.type.email": []string{"http://axschema.org/contact/email"},
	}

	url_ := q.OPEndpointURL
	if strings.Index(url_, "?") == -1 {
		url_ = url_ + "?"
	} else {
		url_ = url_ + "&"
	}

	return url_ + url.Values(p).Encode()
}
Beispiel #7
0
// 同步
func (this *MemberC) Async(ctx *echo.Context) error {
	var rlt AsyncResult
	var form = url.Values(ctx.Request().Form)
	var mut, aut, kvMut, kvAut int
	memberId := GetMemberId(ctx)
	mut, _ = strconv.Atoi(form.Get("member_update_time"))
	aut, _ = strconv.Atoi(form.Get("account_update_time"))
	mutKey := fmt.Sprintf("%s%d", variable.KvMemberUpdateTime, memberId)
	sto.Get(mutKey, &kvMut)
	autKey := fmt.Sprintf("%s%d", variable.KvAccountUpdateTime, memberId)
	sto.Get(autKey, &kvAut)
	if kvMut == 0 {
		m := dps.MemberService.GetMember(memberId)
		kvMut = int(m.UpdateTime)
		sto.Set(mutKey, kvMut)
	}
	//kvAut = 0
	if kvAut == 0 {
		acc := dps.MemberService.GetAccount(memberId)
		kvAut = int(acc.UpdateTime)
		sto.Set(autKey, kvAut)
	}
	rlt.MemberId = memberId
	rlt.MemberUpdated = kvMut != mut
	rlt.AccountUpdated = kvAut != aut
	return ctx.JSON(http.StatusOK, rlt)
}
Beispiel #8
0
func queryString(opts interface{}) string {
	if opts == nil {
		return ""
	}
	value := reflect.ValueOf(opts)
	if value.Kind() == reflect.Ptr {
		value = value.Elem()
	}
	if value.Kind() != reflect.Struct {
		return ""
	}
	items := url.Values(map[string][]string{})
	for i := 0; i < value.NumField(); i++ {
		field := value.Type().Field(i)
		if field.PkgPath != "" {
			continue
		}
		key := field.Tag.Get("qs")
		if key == "" {
			key = strings.ToLower(field.Name)
		} else if key == "-" {
			continue
		}
		addQueryStringValue(items, key, value.Field(i))
	}
	return items.Encode()
}
// ParseControlFile reads debian control file format into map[string][]string
func ParseControlFile(data string) url.Values {
	ret := url.Values(make(map[string][]string))
	arr := strings.Split(data, "\n")
	cur := ""

	for lineno, line := range arr {
		if line == "" {
			// skip empty line
			continue
		}
		lineno++
		tag := ctrlRegexp.Find([]byte(line))
		if tag == nil {
			if _, ok := ret[cur]; !ok {
				log.Printf("Ignoring format error at line#%d: %#v", lineno, line)
				continue
			}
			ret[cur] = append(ret[cur], line)
			continue
		}
		cur = string(tag[0 : len(tag)-1])
		ret[cur] = make([]string, 0)
		if len(line) > len(tag)+1 {
			ret.Add(cur, line[len(tag)+1:])
		}
	}
	return ret
}
Beispiel #10
0
// Round trips the request to the selected proxy and writes back the response
func (p *Handler) proxyRequest(w http.ResponseWriter, r *http.Request) error {
	// Lookup the Proxy registered for the given pair: method, path.
	proxy, params, _ := p.GetRouter().Lookup(r.Method, r.URL.Path)
	if len(params) > 0 {
		// fmt.Printf("params: %+v \n", params)
		r.URL.RawQuery = url.Values(params).Encode() + "&" + r.URL.RawQuery
	}
	if proxy == nil {
		p.logger.Warn("Handler failed to route: %s ", r.URL.Path)
		return errors.FromStatus(http.StatusBadGateway)
	}

	// Create a unique request with sequential ids that will be passed to all interfaces.
	fctx := context.NewFlowContext(r, w, atomic.AddInt64(&p.lastRequestId, 1), nil)

	// The roundtrip thru the whole pipeline of modules
	response, err := proxy.ProcessChain(fctx)

	// Preparing the response back to the client if applicable
	if response != nil {
		httputils.CopyHeaders(w.Header(), response.Header)
		w.WriteHeader(response.StatusCode)
		if response.Body == nil {
			logutils.FileLogger.Warn("Empty body contained on the response")
		} else {
			io.Copy(w, response.Body)
			defer response.Body.Close()
		}
		return nil
	} else {
		return err
	}
}
Beispiel #11
0
func TestResourceNotImplementedMethods(t *testing.T) {

	mux := setupMux(nil, nil)
	go func() {
		http.ListenAndServe(":8188", mux)
	}()

	resp, err := http.Get("http://localhost:8188/rest/somewire")
	checkHttpStatus(t, resp, err, http.StatusNotImplemented)

	body := "{}"
	resp, err = http.Post("http://localhost:8188/rest/somewire", "text/json", strings.NewReader(body))
	checkHttpStatus(t, resp, err, http.StatusNotImplemented)

	data := url.Values(map[string][]string{"nothing": []string{"bogus"}})
	resp, err = http.PostForm("http://localhost:8188/rest/somewire", data)
	checkHttpStatus(t, resp, err, http.StatusNotImplemented)

	resp, err = http.Post("http://localhost:8188/rest/somewire/2", "text/json", strings.NewReader(body))
	checkHttpStatus(t, resp, err, http.StatusBadRequest)

	resp, err = http.Get("http://localhost:8188/rest/somewire/3")
	checkHttpStatus(t, resp, err, http.StatusNotImplemented)

	client := new(http.Client)

	req := makeReq(t, "PUT", "http://localhost:8188/rest/somewire/4", "{}")
	resp, err = client.Do(req)
	checkHttpStatus(t, resp, err, http.StatusNotImplemented)

	req = makeReq(t, "DELETE", "http://localhost:8188/rest/somewire/5", "")
	resp, err = client.Do(req)
	checkHttpStatus(t, resp, err, http.StatusNotImplemented)

}
Beispiel #12
0
func (c *Client) resource(path string, params interface{}) url.URL {
	bp := map[string][]string{
		"v": []string{CLIENT_VERSION},
	}
	if len(c.accessToken) > 0 {
		bp["oauth_token"] = []string{c.accessToken}
	} else {
		bp["client_id"] = []string{c.clientId}
		bp["client_secret"] = []string{c.clientSecret}
	}

	// TODO(dolapo): location params..

	u := url.URL{
		Scheme:   "https",
		Host:     BASE_API_URL,
		Path:     "/v2/" + path,
		RawQuery: url.Values(bp).Encode(),
	}

	if params != nil {
		q, _ := query.Values(params)
		u.RawQuery += "&" + q.Encode()
	}

	return u
}
Beispiel #13
0
// Required by http.Handler interface. This method is invoked by the
// http server and will handle all page routing
func (mux *RERouteMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	requestPath := r.URL.Path

	for _, router := range mux.routers {
		// if this router does not match the url, then continue
		if !router.regex.MatchString(requestPath) {
			continue
		}

		// get submatches: the 1st is the entire url, others are
		// parameters
		submatches := router.regex.FindStringSubmatch(requestPath)
		// just check the length to get better efficiency
		if len(submatches[0]) != len(requestPath) {
			continue
		}

		// encode the parameters into r.URL.RawQuery
		if len(router.params) > 0 {
			values := r.URL.Query()
			for i, match := range submatches[1:] {
				values.Add(router.params[i], match)
			}

			r.URL.RawQuery = url.Values(values).Encode() + "&" + r.URL.RawQuery
		}

		router.handler(w, r)
		return
	}

	http.NotFound(w, r)
}
Beispiel #14
0
// match requests against registered handlers, serve http
func (self *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	for _, h := range self.routes[r.Method] {
		if params, ok := h.parse(r.URL.Path); ok {
			if len(params) > 0 {
				r.URL.RawQuery = url.Values(params).Encode() + "&" + r.URL.RawQuery
			}
			h.ServeHTTP(w, r)
			return
		}
	}
	allowed := make([]string, 0, len(self.routes))
	for method, routes := range self.routes {
		if method == r.Method {
			continue
		}
		for _, h := range routes {
			if _, ok := h.parse(r.URL.Path); ok {
				allowed = append(allowed, method)
			}
		}
	}
	if len(allowed) == 0 {
		//http.NotFound(w, r)
		http.Redirect(w, r, "/error/404", 303)
		return
	}
	w.Header().Add("Allow", strings.Join(allowed, ", "))
	//http.Error(w, "Method Not Allowed", 405)
	http.Redirect(w, r, "/error/405", 303)
}
Beispiel #15
0
// routed an regex route
func (d *Dispatcher) RouteRegex(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Path

	if length := len(d.Router.RegexRoutes); length == 0 {
		return
	}

	for _, route := range d.Router.RegexRoutes {
		//check if Route pattern matches url
		if route.regex.MatchString(path) {
			//get submatches (params)
			matches := route.regex.FindStringSubmatch(path)

			//double check that the Route matches the URL pattern.
			if len(matches[0]) == len(path) {
				if len(route.params) > 0 {
					//add url parameters to the query param map
					values := r.URL.Query()
					for i, match := range matches[1:] {
						values.Add(route.params[i], match)
					}

					//reassemble query params and add to RawQuery
					r.URL.RawQuery = url.Values(values).Encode() + "&" + r.URL.RawQuery
				}

				parts := strings.Split(route.forward, "/")
				d.module, d.controller, d.action = parts[1], parts[2], Util_UCFirst(parts[3])
				d.Match(w, r)
				break
			}
		}
	}

}
Beispiel #16
0
// Like Verify on a parsed URL
func VerifyValues(values url.Values) (grant bool, identifier string, err error) {
	err = nil

	var postArgs url.Values
	postArgs = url.Values(map[string][]string{})

	// Create the url
	URLEndPoint := values.Get("openid.op_endpoint")
	if URLEndPoint == "" {
		log.Printf("no openid.op_endpoint")
		return false, "", errors.New("no openid.op_endpoint")
	}
	for k, v := range values {
		postArgs[k] = v
	}
	postArgs.Set("openid.mode", "check_authentication")
	postContent := postArgs.Encode()

	// Post the request
	var client = new(http.Client)
	postReader := bytes.NewBuffer([]byte(postContent))
	response, err := client.Post(URLEndPoint, "application/x-www-form-urlencoded", postReader)
	if err != nil {
		log.Printf("VerifyValues failed at post")
		return false, "", err
	}

	// Parse the response
	// Convert the reader
	// We limit the size of the response to 1024 bytes but it should be large enough for most cases
	buffer := make([]byte, 1024)
	_, err = response.Body.Read(buffer)
	if err != nil {
		log.Printf("VerifyValues failed reading response")
		return false, "", err
	}

	// Check for ns
	rematch := REVerifyDirectNs.FindSubmatch(buffer)
	if rematch == nil {
		return false, "", errors.New("VerifyValues: ns value not found on the response of the OP")
	}
	nsValue := string(rematch[1])
	if !bytes.Equal([]byte(nsValue), []byte("http://specs.openid.net/auth/2.0")) {
		return false, "", errors.New("VerifyValues: ns value not correct: " + nsValue)
	}

	// Check for is_valid
	match, err := regexp.Match(REVerifyDirectIsValid, buffer)
	if err != nil {
		return false, "", err
	}

	identifier = values.Get("openid.claimed_id")
	if !match {
		log.Printf("no is_valid:true in \"%s\"", buffer)
	}

	return match, identifier, nil
}
Beispiel #17
0
func (c *Client) issueRequest(path, method string, params map[string][]string) (*http.Response, error) {
	var requestID string
	requestIDs, ok := params["requestID"]
	if ok {
		requestID = ""
		if len(requestIDs) > 0 {
			requestID = requestIDs[0]
		}
		delete(params, "requestID")
	}
	v := url.Values(params)
	var suffix string
	var body io.Reader
	if method == "GET" {
		suffix = "?" + v.Encode()
	} else {
		body = strings.NewReader(v.Encode())
	}
	url := strings.TrimRight(c.endpoint, "/") + "/" + strings.Trim(path, "/") + suffix
	req, err := http.NewRequest(method, url, body)
	if err != nil {
		log.Errorf("Got error while creating request: %s", err)
		return nil, err
	}
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Add("Accept", "application/json")
	requestIDHeader, err := config.GetString("request-id-header")
	if err == nil && requestIDHeader != "" {
		req.Header.Add(requestIDHeader, requestID)
	}
	req.SetBasicAuth(c.username, c.password)
	req.Close = true
	return net.Dial5Full300ClientNoKeepAlive.Do(req)
}
Beispiel #18
0
func assertServerFunctional(client http.Client, scheme string) error {
	path := fmt.Sprintf("%s://127.0.0.1:4001/v2/keys/foo", scheme)
	fields := url.Values(map[string][]string{"value": {"bar"}})

	for i := 0; i < 10; i++ {
		time.Sleep(1 * time.Second)

		resp, err := client.PostForm(path, fields)
		// If the status is Temporary Redirect, we should follow the
		// new location, because the request did not go to the leader yet.
		// TODO(yichengq): the difference between Temporary Redirect(307)
		// and Created(201) could distinguish between leader and followers
		for err == nil && resp.StatusCode == http.StatusTemporaryRedirect {
			loc, _ := resp.Location()
			newPath := loc.String()
			resp, err = client.PostForm(newPath, fields)
		}

		if err == nil {
			// Internal error may mean that servers are in leader election
			if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusInternalServerError {
				return errors.New(fmt.Sprintf("resp.StatusCode == %s", resp.Status))
			} else {
				return nil
			}
		}
	}

	return errors.New("etcd server was not reachable in time / had internal error")
}
func (r *delayedRouter) registerVars(req *http.Request, vars map[string]string) {
	values := make(url.Values)
	for key, value := range vars {
		values[":"+key] = []string{value}
	}
	req.URL.RawQuery = url.Values(values).Encode() + "&" + req.URL.RawQuery
}
Beispiel #20
0
// ServeHTTP matches r.URL.Path against its routing table using the rules
// described above.
func (p *PatternServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	for _, ph := range p.handlers[r.Method] {
		if params, ok := ph.try(r.URL.Path); ok {
			if len(params) > 0 {
				r.URL.RawQuery = url.Values(params).Encode() + "&" + r.URL.RawQuery
			}
			ph.ServeHTTP(w, r)
			return
		}
	}

	allowed := make([]string, 0, len(p.handlers))
	for meth, handlers := range p.handlers {
		if meth == r.Method {
			continue
		}

		for _, ph := range handlers {
			if _, ok := ph.try(r.URL.Path); ok {
				allowed = append(allowed, meth)
			}
		}
	}

	if len(allowed) == 0 {
		http.NotFound(w, r)
		return
	}

	w.Header().Add("Allow", strings.Join(allowed, ", "))
	http.Error(w, "Method Not Allowed", 405)
}
Beispiel #21
0
/*
HandleGET registers a HTTP GET handler for path.
handler is a function with an optional url.Values argument.

If the first result value of handler is a struct or struct pointer,
then the struct will be marshalled as JSON response.
If the first result value fo handler is a string,
then it will be used as response body with an auto-detected content type.
An optional second result value of type error will
create a 500 internal server error response if not nil.
All non error responses will use status code 200.

A single optional argument can be passed as object.
In that case handler is interpreted as a method and
object is the address of an object with such a method.

Format of GET handler:

	func([url.Values]) ([struct|*struct|string][, error]) {}

*/
func HandleGET(path string, handler interface{}, object ...interface{}) {
	handlerFunc, in, out := getHandlerFunc(handler, object)
	httpHandler := &httpHandler{
		method:      "GET",
		handlerFunc: handlerFunc,
	}
	// Check handler arguments and install getter
	switch len(in) {
	case 0:
		httpHandler.getArgs = func(request *http.Request) []reflect.Value {
			return nil
		}
	case 1:
		if in[0] != reflect.TypeOf(url.Values(nil)) {
			panic(fmt.Errorf("HandleGET(): handler argument must be url.Values, got %s", in[0]))
		}
		httpHandler.getArgs = func(request *http.Request) []reflect.Value {
			return []reflect.Value{reflect.ValueOf(request.URL.Query())}
		}
	default:
		panic(fmt.Errorf("HandleGET(): handler accepts zero or one arguments, got %d", len(in)))
	}
	httpHandler.writeResult = writeResultFunc(out)
	http.Handle(path, httpHandler)
}
Beispiel #22
0
// match request against registered handlers, server http
func (self *Multiplexer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	for _, h := range self.handlers[r.Method] {
		if params, ok := h.parse(r.URL.Path); ok {
			if len(params) > 0 {
				r.URL.RawQuery = url.Values(params).Encode() + "&" + r.URL.RawQuery
			}
			h.ServeHTTP(w, r)
			return
		}
	}
	allowed := make([]string, 0, len(self.handlers))
	for method, handlers := range self.handlers {
		if method == r.Method {
			continue
		}
		for _, h := range handlers {
			if _, ok := h.parse(r.URL.Path); ok {
				allowed = append(allowed, method)
			}
		}
	}
	if len(allowed) == 0 {
		http.Redirect(w, r, "/error/404", 303)
		return
	}
	w.Header().Add("Allow", strings.Join(allowed, ", "))
	http.Redirect(w, r, "/error/405", 303)
}
Beispiel #23
0
// ParamsFromContext - get the current params value from a given context
func ParamsFromContext(ctx context.Context) url.Values {
	params := ctx.Value("params")
	if params != nil {
		return url.Values(params.(map[string][]string))
	}
	return nil
}
Beispiel #24
0
func TestQuery_Int(t *testing.T) {
	a := assert.New(t)

	form := url.Values(map[string][]string{
		"q1": []string{"1"},
		"q2": []string{"21", "22"},
		"q4": []string{"four"},
	})
	r := &http.Request{Form: form}

	q := &Query{
		abortOnError: false,
		errors:       map[string]string{},
		values:       make(map[string]value, len(form)),
		request:      r,
	}

	q1 := q.Int("q1", 12)
	msgs := q.Parse()
	a.Equal(len(msgs), 0).Equal(*q1, 1)

	q2 := q.Int64("q2", 12)
	msgs = q.Parse()
	a.Equal(len(msgs), 0).Equal(*q2, 21)

	q3 := q.Int64("q3", 32)
	msgs = q.Parse()
	a.Equal(len(msgs), 0).Equal(*q3, 32)

	// 出错的情况下,返回默认值
	q4 := q.Int64("q4", 32)
	msgs = q.Parse()
	a.Equal(len(msgs), 1).Equal(*q4, 32)
}
Beispiel #25
0
func rawCall(token *oauth.Credentials, method string, uri string, opt map[string]string, res interface{}) error {
	param := make(url.Values)
	for k, v := range opt {
		param.Set(k, v)
	}
	oauthClient.SignParam(token, method, uri, param)
	var resp *http.Response
	var err error
	if method == "GET" {
		uri = uri + "?" + param.Encode()
		resp, err = http.Get(uri)
	} else {
		resp, err = http.PostForm(uri, url.Values(param))
	}
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if res == nil {
		return nil
	}
	if *debug {
		return json.NewDecoder(io.TeeReader(resp.Body, os.Stdout)).Decode(&res)
	}
	return json.NewDecoder(resp.Body).Decode(&res)
}
Beispiel #26
0
// Used exclusively by S3 to the best of my knowledge...
func (self *Signer) SignRequestV1(req *http.Request, canon func(*http.Request) (string, error), exp int64) (err error) {
	qstring, err := url.ParseQuery(req.URL.RawQuery)

	if err != nil {
		return
	}

	if exp > 0 {
		qstring["Expires"] = []string{strconv.FormatInt(time.Now().Unix()+exp, 10)}
	} else {
		qstring["Timestamp"] = []string{time.Now().UTC().Format(ISO8601TimestampFormat)}
	}
	delete(qstring, "Signature")
	qstring["AWSAccessKeyId"] = []string{self.AccessKey}

	req.URL.RawQuery = url.Values(qstring).Encode()

	can, err := canon(req)
	if err != nil {
		return
	}

	var sig []byte
	sig, err = self.SignEncoded(crypto.SHA1, can, base64.StdEncoding)

	if err == nil {
		req.URL.RawQuery += "&" + url.Values{"Signature": []string{string(sig)}}.Encode()
	}

	return
}
func TestExcludePage(t *testing.T) {

	ctx := mainNewContext(testConf)

	sessionCookie, err := testLogin(ctx)
	if err != nil {
		t.Fatalf("Failed to log in: %s.\n", err.Error())
	}

	rw := testNewResponseWriter()
	req, err := http.NewRequest("POST", "/exclude", nil)
	if err != nil {
		t.Fatalf("Failed to create test request: %s.\n", err.Error())
	}

	req.AddCookie(sessionCookie)
	req.Form = url.Values(map[string][]string{
		"name":           []string{"#test"},
		"network":        []string{"irc.example.com"},
		"exclude-reason": []string{"Too much trout-slapping."},
	})
	ctx.site.ServeHTTP(rw, req)

	resp, err := rw.GetResponse(req)
	if err != nil {
		t.Fatalf("Failed to parse response: %s.\n", err.Error())
	}

	if resp.StatusCode != 200 {
		t.Fatalf("Status code when displaying exclusions not 200, but %d.\n", resp.StatusCode)
	}

}
Beispiel #28
0
Datei: twty.go Projekt: nobu/twty
func postTweet(token *oauth.Credentials, url_ string, opt map[string]string) error {
	param := make(url.Values)
	for k, v := range opt {
		param.Set(k, v)
	}
	oauthClient.SignParam(token, "POST", url_, param)
	res, err := http.PostForm(url_, url.Values(param))
	if err != nil {
		log.Println("failed to post tweet:", err)
		return err
	}
	defer res.Body.Close()
	if res.StatusCode != 200 {
		log.Println("failed to get timeline:", err)
		return err
	}
	var tweet Tweet
	err = json.NewDecoder(res.Body).Decode(&tweet)
	if err != nil {
		log.Println("failed to parse new tweet:", err)
		return err
	}
	fmt.Println("tweeted:", tweet.Identifier)
	return nil
}
Beispiel #29
0
func postTweet(token *oauth.Credentials, msg string, replyId string) (tweet Tweet, err error) {
	apiurl := "https://api.twitter.com/1.1/statuses/update.json"

	param := make(url.Values)
	param.Set("status", msg)
	if replyId != "" {
		param.Set("in_reply_to_status_id", replyId)
	}

	oauthClient.SignParam(token, "POST", apiurl, param)
	res, err := http.PostForm(apiurl, url.Values(param))
	if err != nil {
		log.Println("failed to post tweet:", err)
		return tweet, err
	}

	defer res.Body.Close()
	if res.StatusCode != 200 {
		log.Println("failed to get timeline:", res.StatusCode)
		log.Println("Body: ", res.Body)
		return tweet, err
	}

	err = json.NewDecoder(res.Body).Decode(&tweet)
	if err != nil {
		log.Println("failed to parse new tweet:", err)
		return tweet, err
	}

	return tweet, nil
}
func testSubmitChannel(ctx *mainContext, name, network, weblink, description string) error {

	req, err := http.NewRequest("POST", "/submit", nil)
	if err != nil {
		return fmt.Errorf("Failed to create test request: %s", err.Error())
	}
	req.Form = url.Values(map[string][]string{
		"name":        []string{name},
		"network":     []string{network},
		"description": []string{description},
	})

	rw := testNewResponseWriter()

	ctx.site.ServeHTTP(rw, req)

	resp, err := rw.GetResponse(req)
	if err != nil {
		return fmt.Errorf("Failed to parse response: %s", err.Error())
	}

	if resp.StatusCode != 200 {
		return fmt.Errorf("Response status code not 200, but %d", resp.StatusCode)
	}

	return nil
}