Exemplo n.º 1
0
func runRevokeTokenTest(t *testing.T, strategy oauth2.AccessTokenStrategy) {
	f := compose.Compose(new(compose.Config), fositeStore, strategy, compose.OAuth2ClientCredentialsGrantFactory, compose.OAuth2TokenIntrospectionFactory, compose.OAuth2TokenRevocationFactory)
	ts := mockServer(t, f, &fosite.DefaultSession{})
	defer ts.Close()

	oauthClient := newOAuth2AppClient(ts)
	token, err := oauthClient.Token(goauth.NoContext)
	assert.Nil(t, err)

	resp, _, errs := gorequest.New().Post(ts.URL+"/revoke").
		SetBasicAuth(oauthClient.ClientID, oauthClient.ClientSecret).
		Type("form").
		SendStruct(map[string]string{"token": "asdf"}).End()
	assert.Len(t, errs, 0)
	assert.Equal(t, 200, resp.StatusCode)

	resp, _, errs = gorequest.New().Post(ts.URL+"/revoke").
		SetBasicAuth(oauthClient.ClientID, oauthClient.ClientSecret).
		Type("form").
		SendStruct(map[string]string{"token": token.AccessToken}).End()
	assert.Len(t, errs, 0)
	assert.Equal(t, 200, resp.StatusCode)

	hres, _, errs := gorequest.New().Get(ts.URL+"/info").
		Set("Authorization", "bearer "+token.AccessToken).
		End()
	require.Len(t, errs, 0)
	assert.Equal(t, http.StatusUnauthorized, hres.StatusCode)
}
Exemplo n.º 2
0
func main() {
	request := gorequest.New()
	_, body, _ := request.Get("http://127.0.0.1:4001/v2/keys/foo").End()
	fmt.Println(body)

	//IT WORKS!!
	save := gorequest.New()
	_, body2, _ := save.Put("http://127.0.0.1:4001/v2/keys/foo?value=hi").End()
	fmt.Println(body2)

	request = gorequest.New()
	_, body, _ = request.Get("http://127.0.0.1:4001/v2/keys/foo").End()
	fmt.Println(body)
}
Exemplo n.º 3
0
func F5Get(url string, clientconfig BIGIPClient) (*simplejson.Json, error) {
	log.Println("[BIGIP] F5Get:  " + url)
	emptyJson := simplejson.New()

	username := clientconfig.RestUsername
	password := clientconfig.RestPassword
	request := gorequest.New().SetBasicAuth(username, password).TLSClientConfig(&tls.Config{InsecureSkipVerify: true})
	resp, body, err := request.Get(url).End()
	if err != nil {
		log.Println("[BIGIP] err: something broke ")
		fmt.Println(err)
		return emptyJson, err[0]
	} else {
		if resp.Status != "200 OK" {
			//
			return emptyJson, errors.New("Did not get 200 OK - got " + resp.Status)
		} else {
			log.Println("[BIGIP] RESP: " + resp.Status)
			log.Println("[BIGIP] RESP: " + body)

			myJson, jsonErr := simplejson.NewFromReader(strings.NewReader(body))
			if jsonErr != nil {
				log.Println("[BIGIP] jsonErr: something broke ")
				fmt.Println(jsonErr)
				return emptyJson, jsonErr
			} else {
				return myJson, nil
				//fmt.Println( myJson.Get("kind") )
			}
		}
	}

	return emptyJson, errors.New("unknown error")
}
Exemplo n.º 4
0
func (d *signin) FetchSession(code string) (Session, error) {
	request := gorequest.New()

	// FIXME does not work if redirect contains query params
	resp, body, errs := request.Get(fmt.Sprintf("%s?verify=%s", d.login, code)).End()
	if len(errs) > 0 {
		return nil, errors.Errorf("Could not exchange code: %s", errs)
	} else if resp.StatusCode != http.StatusOK {
		return nil, errors.Errorf("Could not exchange code, received status: %d", resp.StatusCode)
	}

	var p payload
	if err := json.Unmarshal([]byte(body), &p); err != nil {
		return nil, errors.Errorf("Could not parse answer: %v", err)
	}

	if p.Subject == "" {
		return nil, errors.Errorf("Field subject is empty, got %s", body)
	}

	return &DefaultSession{
		ForceLocalSubject: p.Subject,
		Extra:             map[string]interface{}{},
	}, nil
}
Exemplo n.º 5
0
func NewAPI(username, password string) (*OctosendAPI, error) {
	payload, err := json.Marshal(map[string]string{
		"username": username,
		"password": password,
	})
	if err != nil {
		return nil, err
	}

	url := strings.Join([]string{APIUrl, "3.0/authenticate"}, "/")
	request := gorequest.New().Post(url).Send(string(payload))
	if os.Getenv("OCTOSEND_DEBUG") == "1" {
		request.SetDebug(true)
	}
	resp, body, errs := request.EndBytes()

	if len(errs) > 0 {
		return nil, printErrors(errs)
	}
	if err := httpHandleError([]int{200}, resp.StatusCode, body); err != nil {
		return nil, err
	}

	var response struct {
		Username string `json:"username"`
		ApiKey   string `json:"api-key"`
		Entity   string `json:"entity"`
	}
	if err = json.Unmarshal(body, &response); err != nil {
		return nil, err
	}
	return NewAPIByToken(response.ApiKey), nil
}
Exemplo n.º 6
0
func goreq() *gorequest.SuperAgent {
	request := gorequest.New()
	if os.Getenv("https_proxy") != "" {
		request.Proxy(os.Getenv("https_proxy"))
	}
	return request
}
Exemplo n.º 7
0
func getLegueMatches(league_id int) {
	resp, body, errs := gorequest.New().
		Get("https://api.steampowered.com/IDOTA2Match_570/GetMatchHistory/v0001/").
		Query("key=" + conf.Steamapi).
		Query("league_id=" + strconv.Itoa(league_id)).
		Query("min_players=10").
		End()
	if errs != nil {
		log.Println("(invoker) ERROR:", errs)
		return
	}
	if resp.StatusCode != 200 {
		log.Println("(invoker) ERROR:", resp.StatusCode)
		return
	}
	leagueGamesjs, err := simplejson.NewJson([]byte(body))
	if err != nil {
		log.Println("(invoker) ERROR:", err)
		return
	}

	for i := range leagueGamesjs.Get("result").Get("matches").MustArray() {
		match_id := leagueGamesjs.Get("result").Get("matches").GetIndex(i).Get("match_id").MustInt()
		series_id := leagueGamesjs.Get("result").Get("matches").GetIndex(i).Get("series_id").MustInt()
		series_type := leagueGamesjs.Get("result").Get("matches").GetIndex(i).Get("series_type").MustInt()
		start_time := leagueGamesjs.Get("result").Get("matches").GetIndex(i).Get("start_time").MustInt64()
		if start_time > time.Now().Unix()-86400 {
			seriesIDToSqlite(match_id, series_id, series_type)
			getMatch(match_id)
		}
	}
}
Exemplo n.º 8
0
func NewAPIPathwar(token, debug string) *APIPathwar {
	return &APIPathwar{
		client: gorequest.New(),
		token:  token,
		debug:  debug != "",
	}
}
Exemplo n.º 9
0
func (z *Zone) UpdateRecords(rs []*Record) []error {
	c := RRsetContainer{
		RRsets: []*RRset{
			&RRset{
				Name: rs[0].Name, Type: rs[0].Type, ChangeType: "REPLACE",
				Records: rs,
			},
		},
	}

	_, bytes, errs := gorequest.
		New().
		Patch(fmt.Sprintf("%s/zones/%s", os.Getenv("API_URL"), z.Name)).
		Set("X-API-Key", os.Getenv("API_KEY")).
		Send(c).
		EndBytes()

	if errs != nil {
		return errs
	}
	err := json.Unmarshal(bytes, z)
	if err != nil {
		return []error{err}
	}

	return nil
}
Exemplo n.º 10
0
func isValidAuthorizeRequest(c *HTTPClient, ar *AuthorizeRequest, retry bool) (bool, error) {
	request := gorequest.New()
	resp, body, errs := request.Post(pkg.JoinURL(c.ep, "/guard/allowed")).SetBasicAuth(c.clientConfig.ClientID, c.clientConfig.ClientSecret).Set("Content-Type", "application/json").Send(*ar).End()
	if len(errs) > 0 {
		return false, errors.Errorf("Got errors: %v", errs)
	} else if retry && resp.StatusCode == http.StatusUnauthorized {
		var err error
		if c.clientToken, err = c.clientConfig.Token(oauth2.NoContext); err != nil {
			return false, errors.New(err)
		} else if c.clientToken == nil {
			return false, errors.New("Access token could not be retrieved")
		}
		return isValidAuthorizeRequest(c, ar, false)
	} else if resp.StatusCode != http.StatusOK {
		return false, errors.Errorf("Status code %d is not 200: %s", resp.StatusCode, body)
	}

	if err := json.Unmarshal([]byte(body), &isAllowed); err != nil {
		return false, errors.Errorf("Could not unmarshall body because %s", err.Error())
	}

	if !isAllowed.Allowed {
		return false, errors.New("Authroization denied")
	}
	return isAllowed.Allowed, nil
}
Exemplo n.º 11
0
func isValidAuthenticationRequest(c *HTTPClient, token string, retry bool) (bool, error) {
	data := url.Values{}
	data.Set("token", token)
	request := gorequest.New()
	resp, body, errs := request.Post(pkg.JoinURL(c.ep, "/oauth2/introspect")).Type("form").SetBasicAuth(c.clientConfig.ClientID, c.clientConfig.ClientSecret).SendString(data.Encode()).End()
	if len(errs) > 0 {
		return false, errors.Errorf("Got errors: %v", errs)
	} else if resp.StatusCode != http.StatusOK {
		return false, errors.Errorf("Status code %d is not 200: %s", resp.StatusCode, body)
	}

	if retry && resp.StatusCode == http.StatusUnauthorized {
		var err error
		if c.clientToken, err = c.clientConfig.Token(oauth2.NoContext); err != nil {
			return false, errors.New(err)
		} else if c.clientToken == nil {
			return false, errors.New("Access token could not be retrieved")
		}
		return isValidAuthenticationRequest(c, token, false)
	} else if resp.StatusCode != http.StatusOK {
		return false, fmt.Errorf("Status code %d is not 200", resp.StatusCode)
	}

	var introspect struct {
		Active bool `json:"active"`
	}

	if err := json.Unmarshal([]byte(body), &introspect); err != nil {
		return false, err
	} else if !introspect.Active {
		return false, errors.New("Authentication denied")
	}
	return introspect.Active, nil
}
Exemplo n.º 12
0
func getLeaguePrizePool(leagueid int) {
	resp, body, errs := gorequest.New().
		Get("https://api.steampowered.com/IEconDOTA2_570/GetTournamentPrizePool/v0001/").
		Query("key=" + conf.Steamapi).
		Query("leagueid=" + strconv.Itoa(leagueid)).
		End()
	if errs != nil {
		log.Fatal(errs)
	}
	if resp.StatusCode != 200 {
		log.Println("(riki) ERROR:", resp.StatusCode)
		return
	}
	pooljs, err := simplejson.NewJson([]byte(body))
	if err != nil {
		log.Fatal("(riki) ERROR:", err)
		return
	}

	prize_pool := pooljs.Get("result").Get("prize_pool").MustInt()

	_, err = db.Exec("update leagues set prize_pool=? where id = ?;", prize_pool, leagueid)
	if err != nil {
		log.Fatal("(riki) ERROR:", err)
		return
	}
}
Exemplo n.º 13
0
//
// GetHeroes to SQLite db
//
func getHeroes() {

	resp, body, errs := gorequest.New().
		Get("https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/").
		Query("key=" + conf.Steamapi).
		Query("language=en_us").
		End()
	if errs != nil {
		log.Fatal(errs)
	}
	herojs, err := simplejson.NewJson([]byte(body))
	if err != nil {
		log.Fatal("(riki) ERROR:", err)
		return
	}
	if resp.StatusCode != 200 {
		log.Println("(riki) ERROR:", resp.StatusCode)
		return
	}

	for i := range herojs.Get("result").Get("heroes").MustArray() {
		id := herojs.Get("result").Get("heroes").GetIndex(i).Get("id").MustInt()
		name := herojs.Get("result").Get("heroes").GetIndex(i).Get("name").MustString()
		localized_name := herojs.Get("result").Get("heroes").GetIndex(i).Get("localized_name").MustString()
		heroToSqlite(id, name[14:], localized_name)
	}
}
Exemplo n.º 14
0
Arquivo: store.go Projeto: zacatac/AH8
func writeFare(data []collect.FareData) error {
	for _, option := range data {
		fmt.Println(option)
		request := gorequest.New()
		fareLiteral := `{"id":%d,` +
			`"service":"%s",` +
			`"type":"%s",` +
			`"cost":"%d",` +
			`"eta":"%d",` +
			`"start_lat":%f,` +
			`"start_lon":%f,` +
			`"end_lat":%f,` +
			`"end_lon":%f,` +
			`"time":"%s"}`
		body := fmt.Sprintf(fareLiteral, option.Id, option.Service, option.Type,
			option.Cost, option.Eta,
			option.Start.Lat(), option.Start.Lng(),
			option.End.Lat(), option.End.Lng(), option.Time)
		resp, _, errs := request.Post("https://api-us.clusterpoint.com/100882/car-service-test.json").
			SetBasicAuth("*****@*****.**", "angelhack").
			Send(body).
			End()
		if len(errs) > 0 {
			fmt.Println(resp)
			fmt.Println(errs)
		}
	}
	return nil
}
Exemplo n.º 15
0
func (c *FastPushPlugin) FastPush(cliConnection plugin.CliConnection, appName string, dryRun bool) {
	// Please check what GetApp returns here
	// https://github.com/cloudfoundry/cli/blob/master/plugin/models/get_app.go

	authToken := c.GetAppVersionId(cliConnection, appName)

	if dryRun {
		// NEED TO HANDLE DRY RUN
		c.ui.Warn("warning: No changes will be applied, this is a dry run !!")
	}

	apiEndpoint := c.GetApiEndpoint(cliConnection, appName)
	request := gorequest.New()
	_, body, err := request.Get(apiEndpoint+"/_fastpush/files").Set("x-auth-token", authToken).End()
	if err != nil {
		panic(err)
	}
	remoteFiles := map[string]*lib.FileEntry{}
	json.Unmarshal([]byte(body), &remoteFiles)

	localFiles := lib.ListFiles()

	filesToUpload := c.ComputeFilesToUpload(localFiles, remoteFiles)
	payload, _ := json.Marshal(filesToUpload)
	_, body, err = request.Put(apiEndpoint+"/_fastpush/files").Set("x-auth-token", authToken).Send(string(payload)).End()
	if err != nil {
		panic(err)
	}
	status := lib.Status{}
	json.Unmarshal([]byte(body), &status)
	c.ui.Say(status.Health)
}
Exemplo n.º 16
0
func getTeam(id int) {
	resp, body, errs := gorequest.New().
		Get("https://api.steampowered.com/IDOTA2Match_570/GetTeamInfoByTeamID/v0001/").
		Query("key=" + conf.Steamapi).
		Query("start_at_team_id=" + strconv.Itoa(id)).
		End()
	if errs != nil {
		log.Fatal(errs)
	}
	if resp.StatusCode != 200 {
		log.Println("(riki) ERROR:", resp.StatusCode)
		return
	}
	teamjs, err := simplejson.NewJson([]byte(body))
	if err != nil {
		log.Fatal("(riki) ERROR:", err)
		return
	}

	name := teamjs.Get("result").Get("teams").GetIndex(0).Get("name").MustString()
	tag := teamjs.Get("result").Get("teams").GetIndex(0).Get("tag").MustString()
	logo := teamjs.Get("result").Get("teams").GetIndex(0).Get("logo").MustInt()
	logo_sponsor := teamjs.Get("result").Get("teams").GetIndex(0).Get("logo_sponsor").MustInt()
	country_code := teamjs.Get("result").Get("teams").GetIndex(0).Get("country_code").MustString()
	url := teamjs.Get("result").Get("teams").GetIndex(0).Get("url").MustString()

	teamToSqlite(id, name, tag, logo, logo_sponsor, country_code, url)
}
Exemplo n.º 17
0
func GetUsers() ([]auth.User, error) {
	_, body, errs := gorequest.New().Get(endpoint).End()
	if errs != nil {
		return nil, errors.New("Can't get users from Auth provider")
	} else {
		var loaded []auth.User
		json.Unmarshal([]byte(body), &loaded)

		exist_users := GetAllUsers()

		var user_keys map[string]auth.User = map[string]auth.User{}

		for _, value := range exist_users {
			user_keys[value.Id] = value
		}
		var users []auth.User

		for _, value := range loaded {
			existed, ok := user_keys[value.Id]
			fmt.Println(ok)
			if !ok {
				users = append(users, value)
			} else {
				users = append(users, existed)
			}
		}

		return users, nil
	}
}
Exemplo n.º 18
0
func (api cvedictClient) httpGet(key, url string, resChan chan<- response, errChan chan<- error) {
	var body string
	var errs []error
	var resp *http.Response
	f := func() (err error) {
		//  resp, body, errs = gorequest.New().SetDebug(config.Conf.Debug).Get(url).End()
		resp, body, errs = gorequest.New().Get(url).End()
		if 0 < len(errs) || resp == nil || resp.StatusCode != 200 {
			return fmt.Errorf("HTTP GET error: %v, url: %s, resp: %v", errs, url, resp)
		}
		return nil
	}
	notify := func(err error, t time.Duration) {
		log.Warnf("Failed to HTTP GET. retrying in %s seconds. err: %s", t, err)
	}
	err := backoff.RetryNotify(f, backoff.NewExponentialBackOff(), notify)
	if err != nil {
		errChan <- fmt.Errorf("HTTP Error %s", err)
	}
	cveDetail := cve.CveDetail{}
	if err := json.Unmarshal([]byte(body), &cveDetail); err != nil {
		errChan <- fmt.Errorf("Failed to Unmarshall. body: %s, err: %s", body, err)
	}
	resChan <- response{
		key,
		cveDetail,
	}
}
Exemplo n.º 19
0
func (api cvedictClient) httpPost(key, url string, query map[string]string) ([]cve.CveDetail, error) {
	var body string
	var errs []error
	var resp *http.Response
	f := func() (err error) {
		req := gorequest.New().SetDebug(config.Conf.Debug).Post(url)
		for key := range query {
			req = req.Send(fmt.Sprintf("%s=%s", key, query[key])).Type("json")
		}
		resp, body, errs = req.End()
		if 0 < len(errs) || resp == nil || resp.StatusCode != 200 {
			return fmt.Errorf("HTTP POST error: %v, url: %s, resp: %v", errs, url, resp)
		}
		return nil
	}
	notify := func(err error, t time.Duration) {
		log.Warnf("Failed to HTTP POST. retrying in %s seconds. err: %s", t, err)
	}
	err := backoff.RetryNotify(f, backoff.NewExponentialBackOff(), notify)
	if err != nil {
		return []cve.CveDetail{}, fmt.Errorf("HTTP Error %s", err)
	}

	cveDetails := []cve.CveDetail{}
	if err := json.Unmarshal([]byte(body), &cveDetails); err != nil {
		return []cve.CveDetail{},
			fmt.Errorf("Failed to Unmarshall. body: %s, err: %s", body, err)
	}
	return cveDetails, nil
}
Exemplo n.º 20
0
// Charge - it charges the customer on mpower and returns a response json object which contains the receipt url with other information
// The `confirmToken` is from the customer
// Returns a `boolean` and `error`
// The boolean signifies whether the customer was chargeed or not
// The response json object can be retrieved on the onsite invoice object
//
// Example.
//    if ok, err := onsite.Charge(onsite.Token, "4346"); ok {
//      //doSomething
//    } else {
//
//    }
//
func (on *OnsiteInvoice) Charge(oprToken, confirmToken string) (bool, error) {
	var respData oprResponse
	data := opr{oprToken, confirmToken}
	req := gorequest.New()

	for key, val := range on.Setup.GetHeaders() {
		req.Set(key, val)
	}

	if dataByte, err := json.Marshal(data); err != nil {
		return false, err
	} else {
		if _, body, err := req.Send(bytes.NewBuffer(dataByte).String()).End(); err != nil {
			return false, fmt.Errorf("%v", err)
		} else {
			if err := json.Unmarshal(bytes.NewBufferString(body).Bytes(), &respData); err != nil {
				return false, err
			}

			on.ResponseText = respData.ResponseText
			on.ResponseCode = respData.ResponseCode

			if respData.ResponseCode == "00" {
				on.Description = respData.Description
				on.Status = respData.InvoiceData.Status
				on.ReceiptUrl = respData.InvoiceData.ReceiptUrl
				return true, nil
			} else {
				return false, fmt.Errorf("Failed to charge invoice. Check OPR or confirm token and try again.")
			}
		}
	}
}
Exemplo n.º 21
0
func diffstatRoute(e *Env, c web.C, w http.ResponseWriter, r *http.Request) error {
	if requireAuth(e, w, r) {
		return nil
	}

	sha := r.URL.Query().Get("sha")

	_, body, _ := gorequest.New().Get(fmt.Sprintf("https://api.github.com/repos/topscore/topscore/commits/%s", sha)).
		Param("access_token", e.Session.GithubToken).
		End()

	var commit commitType
	err := json.Unmarshal([]byte(body), &commit)
	check(err)
	fmt.Printf("%+v", commit)

	respBody, err := json.Marshal(struct {
		Stats        statsType `json:"stats"`
		FilesChanged int       `json:"files_changed"`
	}{
		Stats:        commit.Stats,
		FilesChanged: len(commit.Files),
	})
	check(err)

	w.Header().Set("Content-Type", "application/json")
	w.Write(respBody)
	return nil
}
Exemplo n.º 22
0
func sendRequest(userName string, id int, jsonSchemaWithTag string) {
	request := gorequest.New()
	if tag, schema := stringify(jsonSchemaWithTag); tag == "" && schema == "" {
		fmt.Println("error")
	} else {
		str := `{"domainName":"` + userName + `","typeName":` + tag + `,"jsonSchema":` + schema + `}`

		fmt.Printf("%s", str)
		resp, _, err := request.Post(baseURL).
			Set("Content-Type", "application/json").
			Send(str).End()
		if err != nil {
			//spew.Dump(err)
			callBackUser(id, "JSON syntax error")
		} else {

			//	spew.Dump(body)
			//	spew.Dump(resp)
			target := Onion{}
			processResponser(resp, &target)
			spew.Dump(target.Ginger_Id)
			var s string = strconv.Itoa(int(target.Ginger_Id))
			sendRequestByIdForBuild(s, id)
		}
	}
}
Exemplo n.º 23
0
func Call(args ...string) *simplejson.Json {
	method := args[0]
	params := "[]"
	if len(args) > 1 {
		params = args[1]
	}

	postBody := `{"jsonrpc":"2.0","method":"` + method + `","params":` + params + `}`
	// fmt.Println("postBody: " + postBody)

	_, body, errs := gorequest.New().Post(apiUrl).
		Send(postBody).
		End()

	if errs != nil {
		panic(errs)
	}

	js, err := simplejson.NewJson([]byte(body))
	if err != nil {
		log.Fatalln(err)
	}

	return js
}
Exemplo n.º 24
0
func fetchHttp(url string, opts options) response {
	var resp gorequest.Response
	var body string
	var errs []error
	client := gorequest.New()
	switch opts.Method {
	case gorequest.HEAD:
		resp, body, errs = client.Head(url).End()
	case gorequest.GET:
		resp, body, errs = client.Get(url).End()
	case gorequest.POST:
		resp, body, errs = client.Post(url).Query(opts.Body).End()
	case gorequest.PUT:
		resp, body, errs = client.Put(url).Query(opts.Body).End()
	case gorequest.PATCH:
		resp, body, errs = client.Patch(url).Query(opts.Body).End()
	case gorequest.DELETE:
		resp, body, errs = client.Delete(url).End()
	}

	result := response{
		options:    opts,
		Status:     resp.StatusCode,
		StatusText: resp.Status,
		Errors:     errs,
	}
	result.Body = body
	result.Headers = resp.Header
	return result
}
Exemplo n.º 25
0
func isMountebankRunning(mountebankBaseUri string) bool {
	resp, _, errs := gorequest.New().Get(mountebankBaseUri).End()

	Expect(errs).To(HaveLen(0))

	return resp.StatusCode == http.StatusOK
}
Exemplo n.º 26
0
// GetWithParameters Makes a GET request to shopify with the given endpoint and given parameters
func (shopify *Shopify) GetWithParameters(endpoint string, parameters map[string]string) ([]byte, []error) {
	targetURL := shopify.createTargetURLWithParameters(endpoint, parameters)
	request := gorequest.New()
	_, body, errs := request.Get(targetURL).End()

	return []byte(body), errs
}
Exemplo n.º 27
0
// Add exposes a container on the service
func (expose Expose) Add(name string, port int) error {
	var err error
	var query struct {
		LocalIP  string    `json:"localip"`
		Services []Service `json:"services"`
	}

	query.LocalIP, err = localIP()
	if err != nil {
		return err
	}

	query.Services = make([]Service, 1)
	query.Services[0].Service = expose.ContainerHost(name)
	query.Services[0].Port = port

	request := gorequest.New().Post("http://"+expose.url+"/api/service").
		Set("Auth-Username", expose.username).
		Set("Auth-Token", expose.token)
	res, _, errs := request.Send(query).End()

	if len(errs) > 0 {
		return errs[0]
	}

	if res.StatusCode != 200 {
		return fmt.Errorf("Invalid return code from server: %d\n%s", res.StatusCode, res.Body)
	}

	return nil
}
Exemplo n.º 28
0
// List lists currently exposed services
func (expose Expose) List(owned bool) (HostList, error) {
	request := gorequest.New().SetBasicAuth(expose.username, expose.token)
	res, body, errs := request.Get("http://" + expose.url + "/api/vms").End()
	if len(errs) > 0 {
		return HostList{}, errs[0]
	}

	if res.StatusCode != 200 {
		return HostList{}, fmt.Errorf("Invalid return code from server: %d", res.StatusCode)
	}

	el := HostList{}
	err := json.Unmarshal([]byte(body), &el)
	if err != nil {
		return HostList{}, err
	}

	if owned {
		res := HostList{}
		for _, eh := range el {
			components := strings.Split(eh.Hostname, ".")
			user := components[len(components)-1]
			project := components[len(components)-2]
			if user == expose.username && project == "docker" {
				res = append(res, eh)
			}
		}
		return res, nil
	}

	return el, nil
}
Exemplo n.º 29
0
// Delete un-exposes (is that a word?) a container from the service
func (expose Expose) Delete(name string) error {
	var query struct {
		Services []Service `json:"services"`
	}

	query.Services = make([]Service, 1)
	query.Services[0].Service = expose.ContainerHost(name)

	request := gorequest.New().Delete("http://"+expose.url+"/api/service").
		Set("Auth-Username", expose.username).
		Set("Auth-Token", expose.token).
		Set("Content-Type", "application/json")
	res, _, errs := request.Send(query).End()

	if len(errs) > 0 {
		return errs[0]
	}

	if res.StatusCode != 200 {
		return fmt.Errorf("Invalid return code from server: %d\n%s", res.StatusCode, res.Body)

	}

	return nil
}
Exemplo n.º 30
-1
func init() {
	resp, body, err := gorequest.New().
		Get("http://" + config.DbConfig.ServerRoot + ":" +
			strconv.FormatUint(uint64(config.DbConfig.Port), 10) +
			"/listDatabases").End()
	if err != nil {
		fmt.Println("listDatabase error:", err)
		os.Exit(1)
	}
	if resp.StatusCode != 200 {
		fmt.Println("listDatabase status:", resp.Status)
		os.Exit(1)
	}
	type dblist struct {
		Databases []string `json: "databases"`
	}
	var list dblist
	json.Unmarshal([]byte(body), &list)
	found := false
	for _, db := range list.Databases {
		if db == config.DATABASE {
			found = true
			break
		}
	}

	fmt.Println("found database is", found)
	if found == false {
		resp, body, err = gorequest.New().Post("http://" +
			config.DbConf(config.DbConfig).String() +
			"/database/" + config.DATABASE + "/plocal/document").End()
		if err != nil {
			fmt.Println("create database:", err)
		} else {
			fmt.Println(body)
			fmt.Println(resp.Status)
			fmt.Println("Database created")
			gorequest.New().Post("http://" + config.DbConf(config.DbConfig).String() + "/class/" + config.DATABASE + "/" + config.PASTECLASS).End()
			config.Driver.Command("create property " + config.PASTECLASS + "." + config.USER_ID + " string")
			config.Driver.Command("create property " + config.PASTECLASS + "." + config.TITLE + " string")
			config.Driver.Command("create property " + config.PASTECLASS + "." + config.CONTENT + " string")
			config.Driver.Command("create property " + config.PASTECLASS + "." + config.LANGUAGE + " string")
			config.Driver.Command("create property " + config.PASTECLASS + "." + config.PUBLIC + " boolean")

		}
	} else {
		fmt.Println("Database already exists")
	}

}