func ServeDataItemPage(writer http.ResponseWriter, request *http.Request) { if strings.Contains(request.Header.Get("Accept"), "application/json") { writer.Header().Set("Content-Type", "applicaton/json") } else { writer.Header().Set("Content-Type", "text/plain") } stream := StreamByName("ranger") log.Printf("Serving full data for '%s'", request.FormValue("q")) data := stream.LookupData(request.FormValue("q")) if data == nil { log.Printf("Failed to find %s", request.FormValue("q")) writer.WriteHeader(http.StatusNotFound) return } outputBytes, err := json.MarshalIndent(data, "", " ") if err != nil { log.Printf("Failed to format data") writer.WriteHeader(http.StatusInternalServerError) return } writer.Write(outputBytes) }
func ReturnJson(conn http.ResponseWriter, data interface{}) { conn.Header().Set("Content-Type", "text/javascript") if m, ok := data.(map[string]interface{}); ok { statusCode := 0 if t, ok := m["error"].(string); ok && len(t) > 0 { statusCode = http.StatusInternalServerError } if t, ok := m["errorType"].(string); ok { switch t { case "server": statusCode = http.StatusInternalServerError case "input": statusCode = http.StatusBadRequest } } if statusCode != 0 { conn.WriteHeader(statusCode) } } bytes, err := json.MarshalIndent(data, "", " ") if err != nil { BadRequestError(conn, fmt.Sprintf( "JSON serialization error: %v", err)) return } conn.Write(bytes) conn.Write([]byte("\n")) }
func SaveBlockDefs(writer io.Writer, blocks BlockTypeList) (err os.Error) { blockDefs := make(map[string]blockDef) for id := range blocks { block := &blocks[id] if !block.defined { // Don't save undefined blocks. continue } var blockDef *blockDef blockDef, err = newBlockDefFromBlockType(block) if err != nil { return } blockDefs[strconv.Itoa(id)] = *blockDef } data, err := json.MarshalIndent(blockDefs, "", " ") if err != nil { return } _, err = writer.Write(data) return }
func JSONLogger(channel chan *cabin.Event) { for { event := <-channel data, _ := json.MarshalIndent(event, "", " ") fmt.Println(bytes.NewBuffer(data).String()) } }
func output(_object interface{}, _configuration *configuration) os.Error { if _configuration.outputPretty { _json, _error := json.MarshalIndent(_object, "", " ") if _error != nil { return _error } _, _error = _configuration.output.Write(_json) if _error != nil { return _error } _, _error = _configuration.output.Write([]byte("\n")) if _error != nil { return _error } } else { _encoder := json.NewEncoder(_configuration.output) _error := _encoder.Encode(_object) if _error != nil { return _error } } return nil }
func prettyJSON(m map[string]interface{}) string { bs, err := json.MarshalIndent(m, "", " ") if err != nil { return fmt.Sprintf("[JSON error %v on %#v]", err, m) } return string(bs) }
func (w JsonResponse) Success(value interface{}) { w.Header().Set("Content-type", "application/json; charset=utf-8") bytes, err := json.MarshalIndent(value, "", " ") if err != nil { panic(ServerError{err.String()}) } w.Write(bytes) }
func ServeWeb(req *web.Request) { b, err := json.MarshalIndent(vars, "", " ") if err != nil { req.Error(web.StatusInternalServerError, err) return } req.Respond(web.StatusOK, web.HeaderContentType, "application/json; charset=utf-8").Write(b) }
func (r JsonResponse) WriteTo(w http.ResponseWriter) { w.Header().Set("Content-Type", "application/json; charset=utf-8") bytes, err := json.MarshalIndent(r.Msg, "", " ") if err != nil { panic(ServerError(err.String())) } w.Write(bytes) }
func TestDescribe(t *testing.T) { for testn, tt := range describeTests { idx := test.NewFakeIndex() tt.setup(idx) h := NewHandler(idx, owner) js := make(map[string]interface{}) dr := h.NewDescribeRequest() dr.Describe(blobref.MustParse(tt.blob), tt.depth) dr.PopulateJSON(js) got, _ := json.MarshalIndent(js, "", " ") want, _ := json.MarshalIndent(tt.expect, "", " ") if !bytes.Equal(got, want) { t.Errorf("test %d:\nwant: %s\n got: %s", testn, string(want), string(got)) } } }
func main() { compounds := make(map[string]Compound) flag.Parse() if flag.NArg() < 1 { log.Fatal("Need a file to open!") } list, err := os.Open(flag.Arg(0)) if err != nil { log.Fatal(err) } reader := bufio.NewReader(list) spaces := regexp.MustCompile("\x20+") for { line, err := reader.ReadString('\n') if err == os.EOF { break } if err != nil { log.Fatal(err) } line = spaces.ReplaceAllString(line, " ") parts := strings.SplitN(line, " ", 3) if len(parts) < 3 { continue } compound := Compound{strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1]), strings.TrimSpace(parts[2])} _, exists := compounds[compound.Meaning] if exists { log.Printf("Duplicate meaning: %v", compound.Meaning) } compounds[compound.Meaning] = compound } array := make([]Compound, len(compounds)) i := 0 for _, compound := range compounds { array[i] = compound i += 1 } var out string if *html { out = mustache.RenderFile("list.mustache", map[string][]Compound{"compounds": array}) } else { json_list, _ := json.MarshalIndent(array, "", " ") out = string(json_list) } fmt.Print(out) }
func ReturnJson(conn http.ResponseWriter, data interface{}) { conn.SetHeader("Content-Type", "text/javascript") bytes, err := json.MarshalIndent(data, "", " ") if err != nil { BadRequestError(conn, fmt.Sprintf( "JSON serialization error: %v", err)) return } conn.Write(bytes) conn.Write([]byte("\n")) }
func (j *JSONlevel) Print(lvl *Level) { out, err := json.Marshal(lvl.Grid) if err != nil { fmt.Println(err) } fmt.Println(string(out)) out, err = json.MarshalIndent(j, "", "\t") if err != nil { fmt.Println(err) } fmt.Println(string(out)) }
func saveConfig(bc *botConfig) os.Error { _, err := json.MarshalIndent(bc, "", " ") if err != nil { return err } //mv old to path.bak //attempt to write //Fail: attempt to undo mv //success: return nil }
func discoveryHelper(rw http.ResponseWriter, req *http.Request, m map[string]interface{}) { rw.Header().Set("Content-Type", "text/javascript") inCb := false if cb := req.FormValue("cb"); identPattern.MatchString(cb) { fmt.Fprintf(rw, "%s(", cb) inCb = true } bytes, _ := json.MarshalIndent(m, "", " ") rw.Write(bytes) if inCb { rw.Write([]byte{')'}) } }
// Saves the world to a JSON formatted data file. Optionally with indentation // for easy reading/modification. func SaveWorld(file string, world *World, compact bool) (err os.Error) { var data []byte if compact { if data, err = json.Marshal(world); err != nil { return } } else { if data, err = json.MarshalIndent(world, "", " "); err != nil { return } } return ioutil.WriteFile(path.Clean(file), data, 0600) }
func MapToCamliJson(m map[string]interface{}) (string, os.Error) { version, hasVersion := m["camliVersion"] if !hasVersion { return "", NoCamliVersionError } m["camliVersion"] = 0, false jsonBytes, err := json.MarshalIndent(m, "", " ") if err != nil { return "", err } m["camliVersion"] = version buf := new(bytes.Buffer) fmt.Fprintf(buf, "{\"camliVersion\": %v,\n", version) buf.Write(jsonBytes[2:]) return string(buf.Bytes()), nil }
func (c *StickConf) WrConf() os.Error { f, err := os.Open(c.conffile, os.O_WRONLY, 600) if err != nil { return os.NewError("An error occurred while parsing the config file: " + err.String()) } defer f.Close() jsonbytes, err := json.MarshalIndent(c.Conf, "", " ") if err != nil { return os.NewError("An error occurred while marshaling struct: " + err.String()) } _, err = f.Write(jsonbytes) if err != nil { return os.NewError("An error occurred while parsing the config file: " + err.String()) } return nil }
func Connect() Accounts { var account Accounts file, config := gotter.GetConfig("zwitscher") config["ClientToken"] = "lhCgJRAE1ECQzwVXfs5NQ" config["ClientSecret"] = "qk9i30vuzWHspsRttKsYrnoKSw9XBmWHdsis76z4" token, authorized, err := gotter.GetAccessToken(config) if err != nil { log.Fatal("faild to get access token:", err) } if authorized { b, err := json.MarshalIndent(config, "", " ") if err != nil { log.Fatal("failed to store file:", err) } err = ioutil.WriteFile(file, b, 0700) if err != nil { log.Fatal("failed to store file:", err) } } account.Credentials = token return account }
func memstats() string { b, _ := json.MarshalIndent(&runtime.MemStats, "", "\t") return string(b) }
func main() { reply := flag.Bool("r", false, "show replies") list := flag.String("l", "", "show tweets") user := flag.String("u", "", "show user timeline") favorite := flag.String("f", "", "specify favorite ID") //search := flag.String("s", "", "search word") inreply := flag.String("i", "", "specify in-reply ID, if not specify text, it will be RT.") verbose := flag.Bool("v", false, "detail display") flag.Usage = func() { fmt.Fprint(os.Stderr, `Usage of twty: -f ID: specify favorite ID -i ID: specify in-reply ID, if not specify text, it will be RT. -l USER/LIST: show list's timeline (ex: mattn_jp/subtech) -u USER: show user's timeline -r: show replies -v: detail display `) } flag.Parse() file, config := gotter.GetConfig() token, authorized, err := gotter.GetAccessToken(config) if err != nil { log.Fatal("faild to get access token:", err) } if authorized { b, err := json.MarshalIndent(config, "", " ") if err != nil { log.Fatal("failed to store file:", err) } err = ioutil.WriteFile(file, b, 0700) if err != nil { log.Fatal("failed to store file:", err) } } if *reply { tweets, err := gotter.GetTweets(token, "https://api.twitter.com/1/statuses/mentions.json", map[string]string{}) if err != nil { log.Fatal("failed to get tweets:", err) } gotter.ShowTweets(tweets, *verbose) } else if len(*list) > 0 { part := strings.Split(*list, "/", 2) tweets, err := gotter.GetTweets(token, "https://api.twitter.com/1/"+part[0]+"/lists/"+part[1]+"/statuses.json", map[string]string{}) if err != nil { log.Fatal("failed to get tweets:", err) } gotter.ShowTweets(tweets, *verbose) } else if len(*user) > 0 { tweets, err := gotter.GetTweets(token, "https://api.twitter.com/1/statuses/user_timeline.json", map[string]string{"screen_name": *user}) if err != nil { log.Fatal("failed to get tweets:", err) } gotter.ShowTweets(tweets, *verbose) } else if len(*favorite) > 0 { gotter.PostTweet(token, "https://api.twitter.com/1/favorites/create/"+*favorite+".json", map[string]string{}) } else if flag.NArg() == 0 { if len(*inreply) > 0 { gotter.PostTweet(token, "https://api.twitter.com/1/statuses/retweet/"+*inreply+".json", map[string]string{}) } else { tweets, err := gotter.GetTweets(token, "https://api.twitter.com/1/statuses/home_timeline.json", map[string]string{}) if err != nil { log.Fatal("failed to get tweets:", err) } gotter.ShowTweets(tweets, *verbose) } } else { gotter.PostTweet(token, "https://api.twitter.com/1/statuses/update.json", map[string]string{"status": strings.Join(flag.Args(), " "), "in_reply_to_status_id": *inreply}) } }
func doInit() { blobDir := path.Join(osutil.CamliConfigDir(), "keyblobs") os.Mkdir(osutil.CamliConfigDir(), 0700) os.Mkdir(blobDir, 0700) keyId := *flagGpgKey if keyId == "" { keyId = os.Getenv("GPGKEY") } if keyId == "" { // TODO: run and parse gpg --list-secret-keys and see if there's just one and suggest that? Or show // a list of them? log.Fatalf("Initialization requires your public GPG key. Set --gpgkey=<pubid> or set $GPGKEY in your environment. Run gpg --list-secret-keys to find their key IDs.") } if os.Getenv("GPG_AGENT_INFO") == "" { log.Printf("No GPG_AGENT_INFO found in environment; you should setup gnupg-agent. camput will be annoying otherwise.") } // TODO: use same command-line flag as the jsonsign package. // unify them into a shared package just for gpg-related stuff? keyBytes, err := exec.Command("gpg", "--export", "--armor", keyId).Output() if err != nil { log.Fatalf("Error running gpg to export public key: %v", err) } hash := sha1.New() hash.Write(keyBytes) bref := blobref.FromHash("sha1", hash) keyBlobPath := path.Join(blobDir, bref.String()+".camli") if err = ioutil.WriteFile(keyBlobPath, keyBytes, 0644); err != nil { log.Fatalf("Error writing public key blob to %q: %v", keyBlobPath, err) } if ok, err := jsonsign.VerifyPublicKeyFile(keyBlobPath, keyId); !ok { log.Fatalf("Error verifying public key at %q: %v", keyBlobPath, err) } log.Printf("Your Camlistore identity (your GPG public key's blobref) is: %s", bref.String()) _, err = os.Stat(client.ConfigFilePath()) if err == nil { log.Fatalf("Config file %q already exists; quitting without touching it.", client.ConfigFilePath()) } if f, err := os.OpenFile(client.ConfigFilePath(), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600); err == nil { defer f.Close() m := make(map[string]interface{}) m["publicKeyBlobref"] = bref.String() blobPut := make([]map[string]string, 1) blobPut[0] = map[string]string{ "alias": "local", "host": "http://localhost:3179/", "password": "******", } m["blobPut"] = blobPut blobGet := make([]map[string]string, 2) blobGet[0] = map[string]string{ "alias": "keyblobs", "path": "$HOME/.camli/keyblobs", } blobGet[1] = map[string]string{ "alias": "local", "host": "http://localhost:3179/", "password": "******", } m["blobGet"] = blobGet jsonBytes, err := json.MarshalIndent(m, "", " ") if err != nil { log.Fatalf("JSON serialization error: %v", err) } _, err = f.Write(jsonBytes) if err != nil { log.Fatalf("Error writing to %q: %v", client.ConfigFilePath(), err) } log.Printf("Wrote %q; modify as necessary.", client.ConfigFilePath()) } }
func (pr *publishRequest) serveSubject() { dr := pr.ph.Search.NewDescribeRequest() dr.Describe(pr.subject, 3) res, err := dr.Result() if err != nil { log.Printf("Errors loading %s, permanode %s: %v, %#v", pr.req.URL, pr.subject, err, err) pr.pf("<p>Errors loading.</p>") return } subdes := res[pr.subject.String()] if subdes.CamliType == "file" { pr.serveFileDownload(subdes) return } title := subdes.Title() // HTML header + Javascript { jm := make(map[string]interface{}) dr.PopulateJSON(jm) pr.pf("<!doctype html>\n<html>\n<head>\n <title>%s</title>\n", html.EscapeString(title)) for _, filename := range pr.ph.CSSFiles { pr.pf(" <link rel='stylesheet' type='text/css' href='%s'>\n", pr.staticPath(filename)) } for _, filename := range pr.ph.JSFiles { // TODO(bradfitz): Remove this manual dependency hack once Issue 37 is resolved. if filename == "camli.js" { pr.pf(" <script src='%s'></script>\n", pr.staticPath("base64.js")) pr.pf(" <script src='%s'></script>\n", pr.staticPath("Crypto.js")) pr.pf(" <script src='%s'></script>\n", pr.staticPath("SHA1.js")) } pr.pf(" <script src='%s'></script>\n", pr.staticPath(filename)) if filename == "camli.js" && pr.ViewerIsOwner() { pr.pf(" <script src='%s'></script>\n", pr.base+"?camli.mode=config&cb=onConfiguration") } } pr.pf(" <script>\n") pr.pf("var camliViewIsOwner = %v;\n", pr.ViewerIsOwner()) pr.pf("var camliPagePermanode = %q;\n", pr.subject) pr.pf("var camliPageMeta = \n") json, _ := json.MarshalIndent(jm, "", " ") pr.rw.Write(json) pr.pf(";\n </script>\n</head>\n<body>\n") defer pr.pf("</body>\n</html>\n") } if title != "" { pr.pf("<h1>%s</h1>\n", html.EscapeString(title)) } if cref, ok := subdes.ContentRef(); ok { des, err := pr.dr.DescribeSync(cref) if err == nil && des.File != nil { path := []*blobref.BlobRef{pr.subject, cref} downloadURL := pr.SubresFileURL(path, des.File.FileName) pr.pf("<div>File: %s, %d bytes, type %s</div>", html.EscapeString(des.File.FileName), des.File.Size, des.File.MimeType) if des.File.IsImage() { pr.pf("<a href='%s'><img src='%s'></a>", downloadURL, pr.SubresThumbnailURL(path, des.File.FileName, 600)) } pr.pf("<div id='%s' class='camlifile'>[<a href='%s'>download</a>]</div>", cref.DomID(), downloadURL) } } if members := subdes.Members(); len(members) > 0 { pr.pf("<ul>\n") for _, member := range members { des := member.Description() if des != "" { des = " - " + des } var fileLink, thumbnail string if path, fileInfo, ok := member.PermanodeFile(); ok { fileLink = fmt.Sprintf("<div id='%s' class='camlifile'><a href='%s'>file</a></div>", path[len(path)-1].DomID(), html.EscapeString(pr.SubresFileURL(path, fileInfo.FileName)), ) if fileInfo.IsImage() { thumbnail = fmt.Sprintf("<img src='%s'>", pr.SubresThumbnailURL(path, fileInfo.FileName, 200)) } } pr.pf(" <li id='%s'><a href='%s'>%s<span>%s</span></a>%s%s</li>\n", member.DomID(), pr.memberPath(member.BlobRef), thumbnail, html.EscapeString(member.Title()), des, fileLink) } pr.pf("</ul>\n") } }
func (meth *Method) generateCode() { res := meth.r // may be nil if a top-level method a := meth.api p, pn := a.p, a.pn pn("\n// method id %q:", meth.Id()) retTypeComma := responseType(meth.m) if retTypeComma != "" { retTypeComma += ", " } args := meth.NewArguments() methodName := initialCap(meth.name) prefix := "" if res != nil { prefix = initialCap(res.name) } callName := a.GetName(prefix + methodName + "Call") p("\ntype %s struct {\n", callName) p("\ts *Service\n") for _, arg := range args.l { p("\t%s %s\n", arg.goname, arg.gotype) } p("\topt_ map[string]interface{}\n") if meth.supportsMedia() { p("\tmedia_ io.Reader\n") } p("}\n") p("\n%s", asComment("", methodName+": "+jstr(meth.m, "description"))) var servicePtr string if res == nil { p("func (s *Service) %s(%s) *%s {\n", methodName, args, callName) servicePtr = "s" } else { p("func (r *%s) %s(%s) *%s {\n", res.GoType(), methodName, args, callName) servicePtr = "r.s" } p("\tc := &%s{s: %s, opt_: make(map[string]interface{})}\n", callName, servicePtr) for _, arg := range args.l { p("\tc.%s = %s\n", arg.goname, arg.goname) } p("\treturn c\n") p("}\n") for _, opt := range meth.OptParams() { setter := initialCap(opt.name) des := jstr(opt.m, "description") des = strings.Replace(des, "Optional.", "", 1) des = strings.TrimSpace(des) p("\n%s", asComment("", fmt.Sprintf("%s sets the optional parameter %q: %s", setter, opt.name, des))) np := new(namePool) np.Get("c") // take the receiver's name paramName := np.Get(validGoIdentifer(opt.name)) p("func (c *%s) %s(%s %s) *%s {\n", callName, setter, paramName, opt.GoType(), callName) p("c.opt_[%q] = %s\n", opt.name, paramName) p("return c\n") p("}\n") } if meth.supportsMedia() { p("func (c *%s) Media(r io.Reader) *%s {\n", callName, callName) p("c.media_ = r\n") p("return c\n") p("}\n") } pn("\nfunc (c *%s) Do() (%sos.Error) {", callName, retTypeComma) nilRet := "" if retTypeComma != "" { nilRet = "nil, " } pn("var body io.Reader = nil") hasContentType := false if ba := args.bodyArg(); ba != nil { style := "WithoutDataWrapper" if a.needsDataWrapper() { style = "WithDataWrapper" } pn("body, err := googleapi.%s.JSONReader(c.%s)", style, ba.goname) pn("if err != nil { return %serr }", nilRet) pn(`ctype := "application/json"`) hasContentType = true } pn("params := make(url.Values)") // Set this first. if they override it, though, might be gross. We don't expect // XML replies elsewhere. TODO(bradfitz): hide this option in the generated code? pn(`params.Set("alt", "json")`) for _, p := range meth.RequiredQueryParams() { pn("params.Set(%q, fmt.Sprintf(\"%%v\", c.%s))", p.name, p.goCallFieldName()) } for _, p := range meth.RequiredRepeatedQueryParams() { pn("for _, v := range c.%s { params.Add(%q, fmt.Sprintf(\"%%v\", v)) }", p.name, p.name) } for _, p := range meth.OptParams() { pn("if v, ok := c.opt_[%q]; ok { params.Set(%q, fmt.Sprintf(\"%%v\", v)) }", p.name, p.name) } urlStr := resolveRelative(a.apiBaseURL(), jstr(meth.m, "path")) urlStr = strings.Replace(urlStr, "%7B", "{", -1) urlStr = strings.Replace(urlStr, "%7D", "}", -1) p("urls := googleapi.ResolveRelative(%q, %q)\n", a.apiBaseURL(), jstr(meth.m, "path")) if meth.supportsMedia() { pn("if c.media_ != nil {") // Hack guess, since we get a 404 otherwise: //pn("urls = googleapi.ResolveRelative(%q, %q)", a.apiBaseURL(), meth.mediaPath()) // Further hack. Discovery doc is wrong? pn("urls = strings.Replace(urls, %q, %q, 1)", "https://www.googleapis.com/", "https://www.googleapis.com/upload/") pn("}") } for _, arg := range args.forLocation("path") { p("\turls = strings.Replace(urls, \"{%s}\", %s, 1)\n", arg.apiname, arg.cleanExpr("c.")) } pn("urls += \"?\" + params.Encode()") if meth.supportsMedia() { pn("contentLength_, hasMedia_ := googleapi.ConditionallyIncludeMedia(c.media_, &body, &ctype)") } pn("req, _ := http.NewRequest(%q, urls, body)", jstr(meth.m, "httpMethod")) if meth.supportsMedia() { pn("if hasMedia_ { req.ContentLength = contentLength_ }") } if hasContentType { pn(`req.Header.Set("Content-Type", ctype)`) } pn(`req.Header.Set("User-Agent", "google-api-go-client/` + goGenVersion + `")`) pn("res, err := c.s.client.Do(req);") pn("if err != nil { return %serr }", nilRet) pn("if err := googleapi.CheckResponse(res); err != nil { return %serr }", nilRet) if retTypeComma == "" { pn("return nil") } else { pn("ret := new(%s)", responseType(meth.m)[1:]) pn("if err := json.NewDecoder(res.Body).Decode(ret); err != nil { return nil, err }") pn("return ret, nil") } bs, _ := json.MarshalIndent(meth.m, "\t// ", " ") pn("// %s\n", string(bs)) pn("}") }