コード例 #1
0
func LoadJsonPermission(userReader io.Reader, groupReader io.Reader) (jPermission *JsonPermission, err os.Error) {
	// Load users
	usersDecoder := json.NewDecoder(userReader)
	var users Users
	if err = usersDecoder.Decode(&users); err != nil {
		return
	}

	// Load groups
	groupsDecoder := json.NewDecoder(groupReader)
	var groups Groups
	if err = groupsDecoder.Decode(&groups); err != nil {
		return nil, err
	}

	jPermission = &JsonPermission{
		users: make(map[string]*CachedUser),
	}

	// Cache users and merge groups into users.
	for name, user := range users {
		permissions := make([]string, len(user.Permissions))
		for i := range user.Permissions {
			permissions[i] = user.Permissions[i]
		}
		inhPerm := getInheritance(user.Groups, groups)
		for _, perm := range inhPerm {
			permissions = append(permissions, perm)
		}
		jPermission.users[name] = &CachedUser{permissions: permissions}
	}

	// Cache default user.
	defaultUser := &CachedUser{
		permissions: make([]string, 0),
	}
	for _, group := range groups {
		if group.Default {
			for _, perm := range group.Permissions {
				defaultUser.permissions = append(defaultUser.permissions, perm)
			}
			inhPerm := getInheritance(group.Inheritance, groups)
			for _, perm := range inhPerm {
				defaultUser.permissions = append(defaultUser.permissions, perm)
			}
		}
	}
	jPermission.defaultUser = defaultUser
	return jPermission, nil
}
コード例 #2
0
ファイル: securecookie.go プロジェクト: snoreven/securecookie
// deserialize decodes a value using json.
func deserialize(src []byte, dst interface{}) error {
	dec := json.NewDecoder(bytes.NewBuffer(src))
	if err := dec.Decode(dst); err != nil {
		return err
	}
	return nil
}
コード例 #3
0
ファイル: service.go プロジェクト: pombredanne/contacts.go
func retrieveInfo(client oauth2_client.OAuth2Client, apiUrl, id string, m url.Values, value interface{}) (err os.Error) {
	uri := TWITTER_API_ENDPOINT
	for _, s := range []string{apiUrl, id} {
		if len(s) > 0 {
			if uri[len(uri)-1] != '/' {
				uri += "/"
			}
			uri += s
		}
	}
	headers := make(http.Header)
	headers.Set("Accept", "application/json")
	if m == nil {
		m = make(url.Values)
	}
	resp, _, err := oauth2_client.AuthorizedGetRequest(client, headers, uri, m)
	if err != nil {
		return err
	}
	if resp != nil {
		if resp.StatusCode >= 400 {
			var e ErrorResponse
			b, _ := ioutil.ReadAll(resp.Body)
			json.Unmarshal(b, &e)
			if len(e.Error) > 0 {
				err = os.NewError(e.Error)
			} else {
				err = os.NewError(string(b))
			}
		} else {
			err = json.NewDecoder(resp.Body).Decode(value)
		}
	}
	return err
}
コード例 #4
0
ファイル: filereader.go プロジェクト: ipeet/camlistore
// StaticSet returns the whole of the static set members of that directory
func (dr *DirReader) StaticSet() ([]*blobref.BlobRef, os.Error) {
	if dr.staticSet != nil {
		return dr.staticSet, nil
	}
	staticSetBlobref := blobref.Parse(dr.ss.Entries)
	if staticSetBlobref == nil {
		return nil, fmt.Errorf("schema/filereader: Invalid blobref\n")
	}
	rsc, _, err := dr.fetcher.Fetch(staticSetBlobref)
	if err != nil {
		return nil, fmt.Errorf("schema/filereader: fetching schema blob %s: %v", staticSetBlobref, err)
	}
	ss := new(Superset)
	if err = json.NewDecoder(rsc).Decode(ss); err != nil {
		return nil, fmt.Errorf("schema/filereader: decoding schema blob %s: %v", staticSetBlobref, err)
	}
	if ss.Type != "static-set" {
		return nil, fmt.Errorf("schema/filereader: expected \"static-set\" schema blob for %s, got %q", staticSetBlobref, ss.Type)
	}
	for _, s := range ss.Members {
		member := blobref.Parse(s)
		if member == nil {
			return nil, fmt.Errorf("schema/filereader: invalid (static-set member) blobref\n")
		}
		dr.staticSet = append(dr.staticSet, member)
	}
	return dr.staticSet, nil
}
コード例 #5
0
ファイル: main.go プロジェクト: andradeandrey/webrocket
func configure(flags ServerConfig) {
	if flag.NArg() == 1 {
		fname := flag.Arg(0)
		f, err := os.Open(fname)
		if err != nil {
			log.Fatalf("Config reading error: %s\n", err.String())
		}
		dec := json.NewDecoder(f)
		err = dec.Decode(&server)
		if err != nil {
			log.Fatalf("Config parsing error: %s\n", err.String())
		}
		action = "serve"
	}
	flag.Visit(func(flag *flag.Flag) {
		switch flag.Name {
		case "version":
			action = "version"
		case "port":
			server.Port = flags.Port
		case "host":
			server.Host = flags.Host
		case "tls-cert":
			server.TLSCertFile = flags.TLSCertFile
		case "tls-key":
			server.TLSKeyFile = flags.TLSKeyFile
		case "log":
			server.Log = flags.Log
		}
	})
}
コード例 #6
0
ファイル: go.go プロジェクト: kai-zoa/go-runner
func (self *target) loadProfile(packageName string) os.Error {
	file, err := os.Open(packageName + ".gofiles")
	if err != nil {
		return err
	}
	defer file.Close()
	var prof Profile
	if err := json.NewDecoder(file).Decode(&prof); err != nil {
		return err
	}
	if packageName != "main" {
		self.targetName = prof.Target
	}
	for _, entry := range prof.GoFiles {
		// TODO parse wildcard and ~
		if _, exist := self.files[entry]; exist {
			continue
		}
		if src, err := self.ctx.getSource(entry); err != nil {
			return err
		} else if src != nil && src.packageName == packageName {
			self.files[src.filepath] = src
		}
	}
	return nil
}
コード例 #7
0
ファイル: all_test.go プロジェクト: rapgamer/golang-china
func TestServer(t *testing.T) {
	type addResp struct {
		Id     interface{} "id"
		Result Reply       "result"
		Error  string      "error"
	}

	cli, srv := net.Pipe()
	defer cli.Close()
	go ServeConn(srv)
	dec := json.NewDecoder(cli)

	// Send hand-coded requests to server, parse responses.
	for i := 0; i < 10; i++ {
		fmt.Fprintf(cli, `{"method": "Arith.Add", "id": "\u%04d", "params": [{"A": %d, "B": %d}]}`, i, i, i+1)
		var resp addResp
		err := dec.Decode(&resp)
		if err != nil {
			t.Fatalf("Decode: %s", err)
		}
		if resp.Error != "" {
			t.Fatalf("resp.Error: %s", resp.Error)
		}
		if resp.Id.(string) != string(i) {
			t.Fatalf("resp: bad id %q want %q", resp.Id.(string), string(i))
		}
		if resp.Result.C != 2*i+1 {
			t.Fatalf("resp: bad result: %d+%d=%d", i, i+1, resp.Result.C)
		}
	}
}
コード例 #8
0
ファイル: service.go プロジェクト: pombredanne/contacts.go
func retrieveInfo(client oauth2_client.OAuth2Client, id, scope string, value interface{}) (err os.Error) {
	uri := FACEBOOK_GRAPH_API_ENDPOINT
	for _, s := range []string{id, scope} {
		if len(s) > 0 {
			if uri[len(uri)-1] != '/' {
				uri += "/"
			}
			uri += s
		}
	}
	resp, _, err := oauth2_client.AuthorizedGetRequest(client, nil, uri, nil)
	if err != nil {
		return err
	}
	if resp != nil {
		if resp.StatusCode >= 400 {
			e := new(ErrorResponse)
			b, _ := ioutil.ReadAll(resp.Body)
			if err = json.Unmarshal(b, e); err != nil {
				err = os.NewError(string(b))
			} else {
				err = e
			}
		} else {
			err = json.NewDecoder(resp.Body).Decode(value)
		}
	}
	return err
}
コード例 #9
0
ファイル: mock.go プロジェクト: pombredanne/contacts.go
func (p *MockGoogleClient) handleCreateGroup(req *http.Request) (resp *http.Response, err os.Error) {
	//fmt.Printf("calling handleCreateGroup\n")
	b := NewGroupResponse()
	err = json.NewDecoder(req.Body).Decode(b)
	if err != nil {
		panic(fmt.Sprintf("Error creating group: %s\n", err.String()))
		resp, _ = createJSONHttpResponseFromObj(req, NewGroupResponse())
		resp.Status = "500 INTERNAL SERVER ERROR"
		resp.StatusCode = http.StatusInternalServerError
		return
	}
	if b.Entry == nil {
		resp, err = createJSONHttpResponseFromObj(req, NewGroupResponse())
		resp.Status = "400 BAD REQUEST"
		resp.StatusCode = http.StatusBadRequest
		return
	}
	e := b.Entry
	groupId := p.generateId()
	e.Id.Value = groupId
	e.Etag = p.generateEtag()
	e.Updated.Value = time.UTC().Format(GOOGLE_DATETIME_FORMAT)
	p.groupsById[groupId] = e
	r := NewGroupResponse()
	r.Entry = e
	r.Entry.Xmlns = XMLNS_ATOM
	r.Entry.XmlnsGcontact = XMLNS_GCONTACT
	r.Entry.XmlnsBatch = XMLNS_GDATA_BATCH
	r.Entry.XmlnsGd = XMLNS_GD
	//fmt.Printf("Contact Entry: %v\n", c.Name)
	return createJSONHttpResponseFromObj(req, r)
}
コード例 #10
0
ファイル: main.go プロジェクト: adamsxu/twister
// home handles requests to the home page.
func home(req *web.Request) {
	token, err := credentials(req, "tok")
	if err != nil {
		homeLoggedOut(req)
		return
	}
	param := make(web.Values)
	url := "http://api.twitter.com/1/statuses/home_timeline.json"
	oauthClient.SignParam(token, "GET", url, param)
	url = url + "?" + param.FormEncodedString()
	resp, err := http.Get(url)
	if err != nil {
		req.Error(web.StatusInternalServerError, err)
		return
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		req.Error(web.StatusInternalServerError, os.NewError(fmt.Sprint("Status ", resp.StatusCode)))
		return
	}
	var d interface{}
	err = json.NewDecoder(resp.Body).Decode(&d)
	if err != nil {
		req.Error(web.StatusInternalServerError, err)
		return
	}
	homeTempl.Execute(req.Respond(web.StatusOK, web.HeaderContentType, web.ContentTypeHTML), d)
}
コード例 #11
0
ファイル: block_loader.go プロジェクト: nictuku/chunkymonkey
func LoadBlockDefs(reader io.Reader) (blocks BlockTypeList, err os.Error) {
	blocksStr := make(map[string]blockDef)
	decoder := json.NewDecoder(reader)
	err = decoder.Decode(&blocksStr)

	// Find the max block ID so we allocate the correct amount of memory. Also
	// range check the IDs.
	maxId := 0
	for idStr := range blocksStr {
		var id int
		id, err = strconv.Atoi(idStr)
		if err != nil {
			return
		}
		if id < BlockIdMin || id > BlockIdMax {
			err = os.NewError(fmt.Sprintf(
				"Encountered block type with ID %d which is outside the range"+
					"%d <= N <= %d", id, BlockIdMin, BlockIdMax))
			return
		}
		if id > maxId {
			maxId = id
		}
	}

	// Convert map string keys to ints.
	blocks = make(BlockTypeList, maxId+1)
	for idStr, blockDef := range blocksStr {
		var id int
		id, _ = strconv.Atoi(idStr)

		if blocks[id].defined {
			err = os.NewError(fmt.Sprintf(
				"Block ID %d defined more than once.", id))
		}

		var block *BlockType
		block, err = blockDef.LoadBlockType()
		if err != nil {
			return
		}
		block.id = BlockId(id)
		block.defined = true
		blocks[id] = *block
	}

	// Put VoidAspect in any undefined blocks rather than leave it nil, and also
	// set id on each block type.
	for id := range blocks {
		block := &blocks[id]
		block.id = BlockId(id)
		if !block.defined {
			void := makeVoidAspect()
			block.Aspect = void
			void.setAttrs(&block.BlockAttrs)
		}
	}

	return
}
コード例 #12
0
ファイル: jsoninterface.go プロジェクト: gr0gmint/godht
func (this *JSONInterface) Start() {
	for {
		d := json.NewDecoder(this.Conn)
		req := NewJSONRequest()
		err := d.Decode(req)
		if err != nil {
			fmt.Printf("%s\n", err)
			break
		}
		switch req.Action {
		case "stream":
			fmt.Printf("It's a stream request\n")
			port := int32(req.Parameters["port"].(float64))
			nodeid_string := req.Parameters["nodeid"].(string)
			nodeid := make([]byte, 20)
			_, err := fmt.Sscanf(nodeid_string, "%x", &nodeid)
			if err != nil {
				fmt.Printf("%s\n", err)
				break
			}
			fmt.Printf("nodeid: %x\n", nodeid)
			this.PipeStream(nodeid, port)
		case "store":

		}
	}
}
コード例 #13
0
ファイル: config.go プロジェクト: rvijax/camlistore
func parseConfig() {
	configPath := ConfigFilePath()
	f, err := os.Open(configPath)
	switch {
	case err != nil && err.(*os.PathError).Error.(os.Errno) == syscall.ENOENT:
		// TODO: write empty file?
		return
	case err != nil:
		log.Printf("Error opening config file %q: %v", ConfigFilePath(), err)
		return
	}
	defer f.Close()
	dj := json.NewDecoder(f)
	if err := dj.Decode(&config); err != nil {
		extra := ""
		if serr, ok := err.(*json.SyntaxError); ok {
			if _, serr := f.Seek(0, os.SEEK_SET); serr != nil {
				log.Fatalf("seek error: %v", serr)
			}
			line, col, highlight := errorutil.HighlightBytePosition(f, serr.Offset)
			extra = fmt.Sprintf(":\nError at line %d, column %d (file offset %d):\n%s",
				line, col, serr.Offset, highlight)
		}
		log.Fatalf("error parsing JSON object in config file %s%s\n%v",
			ConfigFilePath(), extra, err)
	}
	if err := jsonconfig.EvaluateExpressions(config); err != nil {
		log.Fatalf("error expanding JSON config expressions in %s: %v", configPath, err)
	}

}
コード例 #14
0
ファイル: database.go プロジェクト: ebering/zellij
func LoadDatabase(dir string) Database {
	d := make([]*Motif, 0)
	dirHandle, ok := os.Open(dir)
	if ok != nil {
		panic("database failure" + ok.String())
	}

	dbnames, _ := dirHandle.Readdirnames(0)

LOAD:
	for _, fname := range dbnames {
		if !strings.HasSuffix(fname, ".zellij") {
			continue
		}
		entry, _ := os.Open(path.Join(dir, fname))
		data := make([]*quadratic.Map, 2)
		data[0], data[1] = quadratic.NewMap(), quadratic.NewMap()
		json.NewDecoder(entry).Decode(&data)

		for _, m := range d {
			if m.Frame.Isomorphic(data[0]) {
				m.Variations = append(m.Variations, data[1])
				continue LOAD
			}
		}
		d = append(d, &Motif{fname, data[0], []*quadratic.Map{data[1]}, nil})
	}

	fmt.Fprintf(os.Stderr, "Loaded database with %v frames\n", len(d))

	return d
}
コード例 #15
0
func (p *JSONMediaTypeInputHandler) OutputTo(req wm.Request, cxt wm.Context, writer io.Writer) (int, http.Header, os.Error) {
	defer func() {
		if p.reader != nil {
			if closer, ok := p.reader.(io.Closer); ok {
				closer.Close()
			}
		}
	}()
	//log.Printf("[JSONMTIH]: Calling OutputTo with reader %v\n", p.reader)
	if p.reader == nil {
		return p.handler.HandleJSONObjectInputHandler(req, cxt, writer, nil)
	}
	obj := jsonhelper.NewJSONObject()
	dec := json.NewDecoder(p.reader)
	err := dec.Decode(&obj)
	if err != nil {
		headers := make(http.Header)
		//headers.Set("Content-Type", wm.MIME_TYPE_JSON)
		m := jsonhelper.NewJSONObject()
		w := json.NewEncoder(writer)
		m.Set("status", "error")
		m.Set("message", err.String())
		m.Set("result", nil)
		w.Encode(m)
		return 500, headers, err
	}
	return p.handler.HandleJSONObjectInputHandler(req, cxt, writer, obj)
}
コード例 #16
0
ファイル: twitter.go プロジェクト: mocchira/digestw
func (user *TwUser) Get(r io.Reader) os.Error {
	dec := json.NewDecoder(r)
	if err := dec.Decode(user); err != nil {
		return err
	}
	return nil
}
コード例 #17
0
ファイル: fs.go プロジェクト: ipeet/camlistore
func (fs *CamliFileSystem) fetchSchemaSuperset(br *blobref.BlobRef) (*schema.Superset, os.Error) {
	blobStr := br.String()
	if ss, ok := fs.blobToSchema.Get(blobStr); ok {
		return ss.(*schema.Superset), nil
	}
	log.Printf("schema cache MISS on %q", blobStr)

	rsc, _, err := fs.fetcher.Fetch(br)
	if err != nil {
		return nil, err
	}
	defer rsc.Close()
	jd := json.NewDecoder(rsc)
	ss := new(schema.Superset)
	err = jd.Decode(ss)
	if err != nil {
		log.Printf("Error parsing %s as schema blob: %v", br, err)
		return nil, os.EINVAL
	}
	if ss.Type == "" {
		log.Printf("blob %s is JSON but lacks camliType", br)
		return nil, os.EINVAL
	}
	ss.BlobRef = br
	fs.blobToSchema.Add(blobStr, ss)
	return ss, nil
}
コード例 #18
0
ファイル: twitter.go プロジェクト: mocchira/digestw
func (tl *TwTimeLine) Get(r io.Reader) os.Error {
	dec := json.NewDecoder(r)
	if err := dec.Decode(tl); err != nil {
		return err
	}
	return nil
}
コード例 #19
0
func (c *WebResourceGetTokenCall) Do() (*SiteverificationWebResourceGettokenResponse, os.Error) {
	var body io.Reader = nil
	params := make(url.Values)
	params.Set("alt", "json")
	if v, ok := c.opt_["verificationMethod"]; ok {
		params.Set("verificationMethod", fmt.Sprintf("%v", v))
	}
	if v, ok := c.opt_["identifier"]; ok {
		params.Set("identifier", fmt.Sprintf("%v", v))
	}
	if v, ok := c.opt_["type"]; ok {
		params.Set("type", fmt.Sprintf("%v", v))
	}
	urls := googleapi.ResolveRelative("https://www.googleapis.com/siteVerification/v1/", "token")
	urls += "?" + params.Encode()
	req, _ := http.NewRequest("GET", urls, body)
	req.Header.Set("User-Agent", "google-api-go-client/0.5")
	res, err := c.s.client.Do(req)
	if err != nil {
		return nil, err
	}
	if err := googleapi.CheckResponse(res); err != nil {
		return nil, err
	}
	ret := new(SiteverificationWebResourceGettokenResponse)
	if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
		return nil, err
	}
	return ret, nil
	// {
	//   "description": "Get a verification token for placing on a website or domain.",
	//   "httpMethod": "GET",
	//   "id": "siteVerification.webResource.getToken",
	//   "parameters": {
	//     "identifier": {
	//       "description": "The URL or domain to verify.",
	//       "location": "query",
	//       "type": "string"
	//     },
	//     "type": {
	//       "description": "Type of resource to verify. Can be 'site' (URL) or 'inet_domain' (domain name).",
	//       "location": "query",
	//       "type": "string"
	//     },
	//     "verificationMethod": {
	//       "description": "The method to use for verifying a site or domain.",
	//       "location": "query",
	//       "type": "string"
	//     }
	//   },
	//   "path": "token",
	//   "response": {
	//     "$ref": "SiteverificationWebResourceGettokenResponse"
	//   },
	//   "scopes": [
	//     "https://www.googleapis.com/auth/siteverification"
	//   ]
	// }

}
コード例 #20
0
ファイル: client.go プロジェクト: abneptis/riak
// ListKeys is generally discouraged in production (see http://wiki.basho.com/HTTP-List-Keys.html)
func ListKeys(c Client, b string, outch chan<- string, cc *http.ClientConn) (err os.Error) {
	resp, err := GetItem(c, b, "", http.Header{"Accept": []string{"application/json"}},
		http.Values{
			"keys":  []string{"stream"},
			"props": []string{"false"},
		}, cc)
	if resp != nil && resp.StatusCode == 200 {

		dec := json.NewDecoder(resp.Body)
		bi := BucketDetails{}
		for err = dec.Decode(&bi); err == nil; err = dec.Decode(&bi) {
			for i := range bi.Keys {
				outch <- bi.Keys[i]
			}
		}
		if err == os.EOF {
			err = nil
		}
	} else {
		return debugFailf(os.Stdout, true, "Unexpected response: %s", resp.Status)(resp)
	}
	close(outch)
	return

}
コード例 #21
0
func (c *WebResourceListCall) Do() (*SiteverificationWebResourceListResponse, os.Error) {
	var body io.Reader = nil
	params := make(url.Values)
	params.Set("alt", "json")
	urls := googleapi.ResolveRelative("https://www.googleapis.com/siteVerification/v1/", "webResource")
	urls += "?" + params.Encode()
	req, _ := http.NewRequest("GET", urls, body)
	req.Header.Set("User-Agent", "google-api-go-client/0.5")
	res, err := c.s.client.Do(req)
	if err != nil {
		return nil, err
	}
	if err := googleapi.CheckResponse(res); err != nil {
		return nil, err
	}
	ret := new(SiteverificationWebResourceListResponse)
	if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
		return nil, err
	}
	return ret, nil
	// {
	//   "description": "Get the list of your verified websites and domains.",
	//   "httpMethod": "GET",
	//   "id": "siteVerification.webResource.list",
	//   "path": "webResource",
	//   "response": {
	//     "$ref": "SiteverificationWebResourceListResponse"
	//   },
	//   "scopes": [
	//     "https://www.googleapis.com/auth/siteverification"
	//   ]
	// }

}
コード例 #22
0
//function that fetches the exchange rate from bitcoincharts
func getExchangeRate(c appengine.Context) float32 {

	client := urlfetch.Client(c)
	resp, err := client.Get("http://bitcoincharts.com/t/weighted_prices.json")
	if err != nil {
		log.Print("getExchangeRate err ", err)
		return -1.0
	}

	//decode the json
	dec := json.NewDecoder(resp.Body)

	var f interface{}
	if err2 := dec.Decode(&f); err != nil {
		log.Println("getExchangeRate err2 ", err2)
		return -1.0
	}

	m := f.(map[string]interface{})
	//get the value for USD 24h
	tmptocheck := m["USD"].(map[string]interface{})["24h"]

	switch v := tmptocheck.(type) {
	case string: //if value is string, it converts it
		newValue, _ := strconv.Atof32(tmptocheck.(string))
		//log.Print(newValue)
		return newValue
	default: //otherwise returns a false value (in case no data is fetched or something)
		return -1.0
	}

	return -1.0
}
コード例 #23
0
ファイル: urlshortener.go プロジェクト: mattn/go-urlshortener
func ExpandURL(shortUrl string) (expandedUrl string, err os.Error) {
	param := http.EncodeQuery(map[string][]string{"shortUrl": {shortUrl}})
	res, _, err := http.Get("https://www.googleapis.com/urlshortener/v1/url?" + param)
	if err != nil {
		return
	}
	if res.StatusCode != 200 {
		err = os.NewError("failed to post")
		return
	}
	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return
	}
	var decbuf bytes.Buffer
	decbuf.Write(b)
	dec := json.NewDecoder(&decbuf)
	var out map[string]interface{}
	err = dec.Decode(&out)
	if err != nil {
		return
	}
	expandedUrl = out["longUrl"].(string)
	return
}
コード例 #24
0
ファイル: urlshortener.go プロジェクト: mattn/go-urlshortener
func ShortenURL(longUrl string) (shortenUrl string, err os.Error) {
	var encbuf bytes.Buffer
	enc := json.NewEncoder(&encbuf)
	err = enc.Encode(map[string]string{"longUrl": longUrl})
	if err != nil {
		return
	}
	res, err := http.Post("https://www.googleapis.com/urlshortener/v1/url", "application/json", strings.NewReader(encbuf.String()))
	if err != nil {
		return
	}
	if res.StatusCode != 200 {
		err = os.NewError("failed to post")
		return
	}
	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return
	}
	var decbuf bytes.Buffer
	decbuf.Write(b)
	dec := json.NewDecoder(&decbuf)
	var out map[string]interface{}
	err = dec.Decode(&out)
	if err != nil {
		return
	}
	shortenUrl = out["id"].(string)
	return
}
コード例 #25
0
ファイル: client.go プロジェクト: rapgamer/golang-china
// NewClientCodec returns a new rpc.ClientCodec using JSON-RPC on conn.
func NewClientCodec(conn io.ReadWriteCloser) rpc.ClientCodec {
	return &clientCodec{
		dec:     json.NewDecoder(conn),
		enc:     json.NewEncoder(conn),
		c:       conn,
		pending: make(map[uint64]string),
	}
}
コード例 #26
0
ファイル: server.go プロジェクト: rapgamer/golang-china
// NewServerCodec returns a new rpc.ServerCodec using JSON-RPC on conn.
func NewServerCodec(conn io.ReadWriteCloser) rpc.ServerCodec {
	return &serverCodec{
		dec:     json.NewDecoder(conn),
		enc:     json.NewEncoder(conn),
		c:       conn,
		pending: make(map[uint64]*json.RawMessage),
	}
}
コード例 #27
0
func (c *BadgesGetCall) Do() (*Badge, os.Error) {
	var body io.Reader = nil
	params := make(url.Values)
	params.Set("alt", "json")
	urls := googleapi.ResolveRelative("https://www.googleapis.com/orkut/v2/", "people/{userId}/badges/{badgeId}")
	urls = strings.Replace(urls, "{userId}", cleanPathString(c.userId), 1)
	urls = strings.Replace(urls, "{badgeId}", strconv.Itoa64(c.badgeId), 1)
	urls += "?" + params.Encode()
	req, _ := http.NewRequest("GET", urls, body)
	req.Header.Set("User-Agent", "google-api-go-client/0.5")
	res, err := c.s.client.Do(req)
	if err != nil {
		return nil, err
	}
	if err := googleapi.CheckResponse(res); err != nil {
		return nil, err
	}
	ret := new(Badge)
	if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
		return nil, err
	}
	return ret, nil
	// {
	//   "description": "Retrieves a badge from a user.",
	//   "httpMethod": "GET",
	//   "id": "orkut.badges.get",
	//   "parameterOrder": [
	//     "userId",
	//     "badgeId"
	//   ],
	//   "parameters": {
	//     "badgeId": {
	//       "description": "The ID of the badge that will be retrieved.",
	//       "format": "int64",
	//       "location": "path",
	//       "required": true,
	//       "type": "string"
	//     },
	//     "userId": {
	//       "description": "The ID of the user whose badges will be listed. Can be me to refer to caller.",
	//       "location": "path",
	//       "required": true,
	//       "type": "string"
	//     }
	//   },
	//   "path": "people/{userId}/badges/{badgeId}",
	//   "response": {
	//     "$ref": "Badge"
	//   },
	//   "scopes": [
	//     "https://www.googleapis.com/auth/orkut",
	//     "https://www.googleapis.com/auth/orkut.readonly"
	//   ]
	// }

}
コード例 #28
0
func (c *AdclientsListCall) Do() (*AdClients, os.Error) {
	var body io.Reader = nil
	params := make(url.Values)
	params.Set("alt", "json")
	if v, ok := c.opt_["maxResults"]; ok {
		params.Set("maxResults", fmt.Sprintf("%v", v))
	}
	if v, ok := c.opt_["pageToken"]; ok {
		params.Set("pageToken", fmt.Sprintf("%v", v))
	}
	urls := googleapi.ResolveRelative("https://www.googleapis.com/adsense/v1/", "adclients")
	urls += "?" + params.Encode()
	req, _ := http.NewRequest("GET", urls, body)
	req.Header.Set("User-Agent", "google-api-go-client/0.5")
	res, err := c.s.client.Do(req)
	if err != nil {
		return nil, err
	}
	if err := googleapi.CheckResponse(res); err != nil {
		return nil, err
	}
	ret := new(AdClients)
	if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
		return nil, err
	}
	return ret, nil
	// {
	//   "description": "List all ad clients in this AdSense account.",
	//   "httpMethod": "GET",
	//   "id": "adsense.adclients.list",
	//   "parameters": {
	//     "maxResults": {
	//       "description": "The maximum number of ad clients to include in the response, used for paging.",
	//       "format": "int32",
	//       "location": "query",
	//       "maximum": "10000",
	//       "minimum": "0",
	//       "type": "integer"
	//     },
	//     "pageToken": {
	//       "description": "A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of \"nextPageToken\" from the previous response.",
	//       "location": "query",
	//       "type": "string"
	//     }
	//   },
	//   "path": "adclients",
	//   "response": {
	//     "$ref": "AdClients"
	//   },
	//   "scopes": [
	//     "https://www.googleapis.com/auth/adsense",
	//     "https://www.googleapis.com/auth/adsense.readonly"
	//   ]
	// }

}
コード例 #29
0
ファイル: service.go プロジェクト: pombredanne/contacts.go
func UpdateGroup(client oauth2_client.OAuth2Client, userId, projection string, original, value *ContactGroup) (response *GroupResponse, err os.Error) {
	var useUserId string
	if len(userId) <= 0 {
		useUserId = GOOGLE_DEFAULT_USER_ID
	} else {
		useUserId = url.QueryEscape(userId)
	}
	if len(projection) <= 0 {
		projection = GOOGLE_DEFAULT_PROJECTION
	}
	headers := make(http.Header)
	headers.Set("GData-Version", "3.0")
	headers.Set("If-Match", original.Etag)
	m := make(url.Values)
	if len(m.Get(CONTACTS_ALT_PARAM)) <= 0 {
		m.Set(CONTACTS_ALT_PARAM, "json")
	}
	uri := GOOGLE_GROUPS_API_ENDPOINT
	for _, s := range []string{useUserId, projection, original.GroupId()} {
		if len(s) > 0 {
			if uri[len(uri)-1] != '/' {
				uri += "/"
			}
			uri += s
		}
	}
	entry := &GroupEntryUpdateRequest{Entry: value}
	value.Xmlns = XMLNS_ATOM
	value.XmlnsGcontact = XMLNS_GCONTACT
	value.XmlnsBatch = XMLNS_GDATA_BATCH
	value.XmlnsGd = XMLNS_GD
	value.Etag = original.Etag
	value.Id = original.Id
	value.Updated.Value = time.UTC().Format(GOOGLE_DATETIME_FORMAT)
	value.Categories = make([]AtomCategory, 1)
	value.Categories[0].Scheme = ATOM_CATEGORY_SCHEME_KIND
	value.Categories[0].Term = ATOM_CATEGORY_TERM_GROUP
	buf, err := json.Marshal(entry)
	if err != nil {
		return
	}
	resp, _, err := oauth2_client.AuthorizedPutRequestBytes(client, headers, uri, m, buf)
	if err != nil {
		return
	}
	if resp != nil {
		if resp.StatusCode >= 400 {
			b, _ := ioutil.ReadAll(resp.Body)
			err = os.NewError(string(b))
		} else {
			response = new(GroupResponse)
			err = json.NewDecoder(resp.Body).Decode(response)
		}
	}
	return
}
コード例 #30
0
func (c *TrainedmodelsPredictCall) Do() (*Output, os.Error) {
	var body io.Reader = nil
	body, err := googleapi.WithoutDataWrapper.JSONReader(c.input)
	if err != nil {
		return nil, err
	}
	ctype := "application/json"
	params := make(url.Values)
	params.Set("alt", "json")
	urls := googleapi.ResolveRelative("https://www.googleapis.com/prediction/v1.4/", "trainedmodels/{id}/predict")
	urls = strings.Replace(urls, "{id}", cleanPathString(c.id), 1)
	urls += "?" + params.Encode()
	req, _ := http.NewRequest("POST", urls, body)
	req.Header.Set("Content-Type", ctype)
	req.Header.Set("User-Agent", "google-api-go-client/0.5")
	res, err := c.s.client.Do(req)
	if err != nil {
		return nil, err
	}
	if err := googleapi.CheckResponse(res); err != nil {
		return nil, err
	}
	ret := new(Output)
	if err := json.NewDecoder(res.Body).Decode(ret); err != nil {
		return nil, err
	}
	return ret, nil
	// {
	//   "description": "Submit model id and request a prediction",
	//   "httpMethod": "POST",
	//   "id": "prediction.trainedmodels.predict",
	//   "parameterOrder": [
	//     "id"
	//   ],
	//   "parameters": {
	//     "id": {
	//       "description": "The unique name for the predictive model.",
	//       "location": "path",
	//       "required": true,
	//       "type": "string"
	//     }
	//   },
	//   "path": "trainedmodels/{id}/predict",
	//   "request": {
	//     "$ref": "Input"
	//   },
	//   "response": {
	//     "$ref": "Output"
	//   },
	//   "scopes": [
	//     "https://www.googleapis.com/auth/prediction"
	//   ]
	// }

}