Exemplo n.º 1
1
func Get(w http.ResponseWriter, r *http.Request) {
	w.SetHeader("Content-Type", "application/json")
	lock.Lock()
	e := json.NewEncoder(w)
	e.Encode(server)
	lock.Unlock()
}
func (p *JSONMediaTypeHandler) OutputTo(req wm.Request, cxt wm.Context, writer io.Writer, resp wm.ResponseWriter) {
	buf := bytes.NewBufferString("")
	obj := jsonhelper.NewJSONObject()
	enc := json.NewEncoder(buf)
	obj.Set("status", "success")
	obj.Set("result", p.obj)
	err := enc.Encode(obj)
	if err != nil {
		//resp.Header().Set("Content-Type", wm.MIME_TYPE_JSON)
		if !p.writtenStatusHeader {
			resp.WriteHeader(500)
			p.writtenStatusHeader = true
		}
		m := jsonhelper.NewJSONObject()
		w := json.NewEncoder(writer)
		m.Set("status", "error")
		m.Set("message", err.String())
		m.Set("result", nil)
		w.Encode(m)
		return
	}
	//resp.Header().Set("Content-Type", wm.MIME_TYPE_JSON)
	resp.Header().Set("Content-Length", strconv.Itoa(buf.Len()))
	if p.lastModified != nil {
		resp.Header().Set("Last-Modified", p.lastModified.Format(http.TimeFormat))
	}
	if len(p.etag) > 0 {
		resp.Header().Set("ETag", strconv.Quote(p.etag))
	}
	handler := wm.NewPassThroughMediaTypeHandler(wm.MIME_TYPE_JSON, ioutil.NopCloser(bytes.NewBuffer(buf.Bytes())), int64(buf.Len()), p.lastModified)
	handler.OutputTo(req, cxt, writer, resp)
}
Exemplo n.º 3
0
func (p *JsonDirectoryListing) OutputTo(req Request, cxt Context, writer io.Writer, resp ResponseWriter) {
	result := new(jsonDirectoryEntryResult)
	result.Path = p.urlPath
	var err os.Error
	defer func() {
		if p.file != nil {
			p.file.Close()
			p.file = nil
		}
	}()
	if p.file == nil {
		p.file, err = os.Open(p.fullPath)
		if err != nil {
			result.Status = "error"
			result.Message = err.String()
			result.Result = make([]jsonDirectoryEntry, 0)
			encoder := json.NewEncoder(writer)
			encoder.Encode(result)
			return
		}
	}
	fileInfos, err := p.file.Readdir(-1)
	if err != nil {
		result.Status = "error"
		result.Message = err.String()
		result.Result = make([]jsonDirectoryEntry, 0)
		encoder := json.NewEncoder(writer)
		encoder.Encode(result)
		return
	}
	entries := make([]jsonDirectoryEntry, len(fileInfos))
	for i, fileInfo := range fileInfos {
		entries[i].Filename = fileInfo.Name
		entries[i].Path = path.Join(p.urlPath, fileInfo.Name)
		entries[i].Size = fileInfo.Size
		entries[i].IsDirectory = fileInfo.IsDirectory()
		if fileInfo.IsDirectory() {
			entries[i].IsDirectory = true
			entries[i].Size = 0
		} else {
			entries[i].IsDirectory = false
			entries[i].Size = fileInfo.Size
		}
		entries[i].LastModified = time.SecondsToUTC(int64(fileInfo.Mtime_ns / 1e9)).Format(time.RFC3339)
	}
	result.Status = "success"
	result.Message = ""
	result.Result = entries
	encoder := json.NewEncoder(writer)
	encoder.Encode(result)
}
Exemplo n.º 4
0
func (p *InMemoryDataStore) Encode(w io.Writer) os.Error {
	v, err := jsonhelper.MarshalWithOptions(p, dm.UTC_DATETIME_FORMAT)
	if err != nil {
		return err
	}
	return json.NewEncoder(w).Encode(v)
}
Exemplo n.º 5
0
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
}
Exemplo n.º 6
0
func postPosition(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	gid, _ := strconv.Atoi(r.FormValue("gid"))
	pid, _ := strconv.Atoi(r.FormValue("pid"))
	lat, _ := strconv.Atoi(r.FormValue("lat"))
	lng, _ := strconv.Atoi(r.FormValue("lng"))
	now := datastore.SecondsToTime(time.Seconds())

	go savePlayer(c, &Player{pid, gid, lat, lng, now})

	q := datastore.NewQuery("Player").
		Filter("GameId =", gid)
	players := make([]Player, 0, 10)
	for t := q.Run(c); ; {
		var p Player
		_, err := t.Next(&p)
		if err == datastore.Done {
			break
		}
		if err != nil {
			serveError(c, w, err)
			return
		}
		if p.PlayerId != pid {
			players = append(players, p)
		}
	}
	m := map[string]interface{}{"players": players, "dead": false}
	enc := json.NewEncoder(w)
	enc.Encode(m)
}
Exemplo n.º 7
0
func main() {
	flag.Parse()
	ZellijTilings, reset = zellij.TileSkeleton(skeleton, tileSymmetry, false)
	Frame := zellij.SkeletonFrame(skeleton)
	symmetryCounts := make(map[string]int)
	for T := range ZellijTilings {
		symmetryGroup := zellij.DetectSymmetryGroup(T)
		filename := fmt.Sprintf("%v-%v-%d", skeleton, symmetryGroup, symmetryCounts[symmetryGroup]+1)
		symmetryCounts[symmetryGroup]++
		save, err := os.Create(path.Join(dir, filename+".zellij"))
		if err != nil {
			panic("file error")
		}
		enc := json.NewEncoder(save)
		enc.Encode([]*quadratic.Map{Frame, T})
		save.Close()
		image := cairo.NewSurface(path.Join(dir, "svg", filename+".svg"), 72*5, 72*5)
		image.SetSourceRGB(0., 0., 0.)
		image.SetLineWidth(.1)
		image.Translate(72*2.5, 72*2.5)
		image.Scale(4., 4.)
		T.ColourFaces(image, zellij.PlainBrush)
		image.Finish()
	}
}
Exemplo n.º 8
0
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
}
Exemplo n.º 9
0
func main() {
	var (
		err          os.Error
		clientId     string
		clientSecret string
	)

	if clientId, clientSecret, err = getClientInfo(); err != nil {
		panic(err)
	}
	transport := google.MakeOauthTransport(clientId, clientSecret, "")

	var accessCode string
	if accessCode, err = getAccessCode(transport.Config); err != nil {
		panic(err)
	}
	if _, err = transport.Exchange(accessCode); err != nil {
		panic(err)
	}

	fmt.Printf("\nYour Google Storage auth object:\n\n")
	enc := json.NewEncoder(os.Stdout)
	authObj := map[string]string{
		"client_id":     transport.ClientId,
		"client_secret": transport.ClientSecret,
		"refresh_token": transport.RefreshToken,
	}
	enc.Encode(authObj)
	fmt.Print("\n")
}
Exemplo n.º 10
0
Arquivo: view.go Projeto: snim2/howl
/* Check the uniqueness of a Uid.
 *
 * FIXME: RESTify this!
 */
func CheckUidHandler(w http.ResponseWriter, r *http.Request) {
	log.Println("CheckUidHandler got request with method: " + r.Method)
	if r.Method == "POST" {
		context := appengine.NewContext(r)
		isUnique := controller.IsUidUnique(context, r.FormValue("uid"))
		encoder := json.NewEncoder(w)
		type UidResponse struct {
			Uid       string
			Available string
		}
		response := new(UidResponse)
		response.Uid = r.FormValue("uid")
		log.Println("Result from IsUidUnique is: " + strconv.Btoa(isUnique) + " : " + reflect.TypeOf(isUnique).String())
		if isUnique {
			log.Println("Username " + response.Uid + " is available")
			response.Available = "available"
		} else {
			log.Println("Username " + response.Uid + " is not available")
			response.Available = "not available"
		}
		log_, _ := json.Marshal(&response)
		log.Println("Sending to JQuery: " + string(log_))
		if err := encoder.Encode(&response); err != nil {
			log.Println("Cannot send JSON to AJAX code: " + err.String())
		}
	}
	return
}
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)
}
Exemplo n.º 12
0
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	s.mu.Lock()
	defer s.mu.Unlock()
	w.SetHeader("Content-Type", "application/json")
	e := json.NewEncoder(w)
	e.Encode(s.series)
}
Exemplo n.º 13
0
// 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),
	}
}
Exemplo n.º 14
0
// 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),
	}
}
Exemplo n.º 15
0
// serialize encodes a value using json.
func serialize(src interface{}) ([]byte, error) {
	buf := new(bytes.Buffer)
	enc := json.NewEncoder(buf)
	if err := enc.Encode(src); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}
Exemplo n.º 16
0
// Open a capture session, attempt to parse any requests to port 80 and
// serialise to stdout as JSON.
func main() {
	out = bufio.NewWriter(os.Stdout)
	errout = bufio.NewWriter(os.Stderr)

	c := OpenCaptureOrDie()
	enc := json.NewEncoder(os.Stdout)
	for pkt := c.Next(); pkt != nil; pkt = c.Next() {
		pkt.Decode()
		SerialisePacket(pkt, enc)
	}
}
Exemplo n.º 17
0
func EncodeToFile(filename string, object interface{}) (e os.Error) {
	file, e := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, 0755)
	if e != nil {
		fmt.Printf("Failed to open %s, %s.\n", filename, e)
		return
	}
	enc := json.NewEncoder(file)
	e = enc.Encode(object)
	if e != nil {
		fmt.Printf("Failed to encode JSON object: %s. (Object represented as %#v).\n", e, object)
		return
	}
	return
}
Exemplo n.º 18
0
func (wrap MarshalStyle) JSONReader(v interface{}) (io.Reader, os.Error) {
	buf := new(bytes.Buffer)
	if wrap {
		buf.Write([]byte(`{"data": `))
	}
	err := json.NewEncoder(buf).Encode(v)
	if err != nil {
		return nil, err
	}
	if wrap {
		buf.Write([]byte(`}`))
	}
	return buf, nil
}
// GET /<domain>
func (this RestJsonMongo) Index(rw http.ResponseWriter, values url.Values, header http.Header) {
	logger.Debug("Index():%v,%v", values, header)
	items, err := this.Store.Find(values)
	if err != nil {
		http.Error(rw, err.String(), http.StatusBadRequest)
		return
	}

	handle := ItemsHandle{Items: items, NumberOfItems: len(items)}
	if err := json.NewEncoder(rw).Encode(handle); err != nil {
		logger.Warn(err)
		http.Error(rw, err.String(), http.StatusBadRequest)
	}
}
Exemplo n.º 20
0
Arquivo: main.go Projeto: kenu/You.RL
func Shorten(w http.ResponseWriter, r *http.Request) {
	var key string
	for key = genKey(); store.Check(&key) == false; {
	}

	long_url := r.FormValue("url")

	store.Put(&key, &long_url)

	v := make(map[string]string)
	v["url"] = "http://" + *hostName + "/" + key

	enc := json.NewEncoder(w)
	enc.Encode(&v)
}
Exemplo n.º 21
0
// Signs the Content
func signHandler(w http.ResponseWriter, r *http.Request) {
	dec := json.NewDecoder(r.Body)
	var data Signature
	dec.Decode(&data)
	keyBytes := []byte(data.Key)
	content := data.Content
	mac := hmac.NewSHA1(keyBytes)
	mac.Write([]byte(content))

	out := make([]byte, base64.StdEncoding.EncodedLen(len(mac.Sum())))
	base64.StdEncoding.Encode(out, mac.Sum())

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(&Signature{string(out), content, data.Key})
}
Exemplo n.º 22
0
func OutputErrorMessage(writer io.Writer, message string, result interface{}, statusCode int, headers http.Header) (int, http.Header, os.Error) {
	if statusCode == 0 {
		statusCode = 500
	}
	if headers == 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", message)
	m.Set("result", result)
	w.Encode(m)
	return statusCode, headers, nil
}
Exemplo n.º 23
0
func Compile(w http.ResponseWriter, req *http.Request) {
	resp := new(Response)
	out, err := compile(req)
	if err != nil {
		if out != nil {
			resp.Errors = string(out)
		} else {
			resp.Errors = err.String()
		}
	} else {
		resp.Output = string(out)
	}
	if err := json.NewEncoder(w).Encode(resp); err != nil {
		log.Println(err)
	}
}
// GET /<domain>/id
func (this RestJsonMongo) Find(rw http.ResponseWriter, id string) {
	logger.Debug("Find(%v)", id)
	storedItem, err := this.Store.Get(id)
	if storedItem == nil {
		http.Error(rw, fmt.Sprintf("item %v not found", id), http.StatusNotFound)
		return
	}

	if err != nil {
		http.Error(rw, err.String(), http.StatusBadRequest)
		return
	}

	if err := json.NewEncoder(rw).Encode(storedItem); err != nil {
		http.Error(rw, err.String(), http.StatusBadRequest)
	}
}
Exemplo n.º 25
0
func New(_store Store, _hasher hasher.Hasher) (_tree *Tree) {
	_tree = new(Tree)
	_tree.store = _store
	_tree.hasher = _hasher
	_tree.gobBuffer = bytes.NewBuffer(make([]byte, 0, 1024*1024))
	_tree.gobEncoder = gob.NewEncoder(_tree.gobBuffer)
	_tree.gobCache = gobCache{_tree.gobBuffer, _tree.gobEncoder, nil}
	_tree.jsonBuffer = bytes.NewBuffer(make([]byte, 0, 1024*1024))
	_tree.jsonEncoder = json.NewEncoder(_tree.jsonBuffer)
	_tree.jsonCache = jsonCache{_tree.jsonBuffer, _tree.jsonEncoder, nil}
	_root := &_tree.root
	_root.tree = _tree
	_root.path = make([]string, 0)
	_root.gobCache = gobCache{_tree.gobBuffer, _tree.gobEncoder, nil}
	_root.jsonCache = jsonCache{_tree.jsonBuffer, _tree.jsonEncoder, nil}
	_root.setDirty()
	return _tree
}
Exemplo n.º 26
0
func getContext() *Context {
	mutex.Lock()
	ctx := free
	if ctx == nil {
		mutex.Unlock()
		ctx = &Context{}
		ctx.buf = &bytes.Buffer{}
		ctx.enc = json.NewEncoder(ctx.buf)
		ctx.req = &request{}
	} else {
		free = ctx.next
		mutex.Unlock()
		ctx.buf.Reset()
		*ctx.req = request{}
	}
	*ctx.req = request{}
	return ctx
}
Exemplo n.º 27
0
func main() {
	flag.Parse()
	q, err := GetQueue()
	if err != nil {
		log.Fatalf("Couldn't create queue: %v\n", err)
	}
	id, err := GetAWSIdentity()
	if err != nil {
		log.Fatalf("Couldn't get identity: %v\n", err)
	}
	msgs, err := q.FetchMessages(id, *max, *timeout)
	if err != nil {
		log.Fatalf("Couldn't pop from queue: %v\n", err)
	}
	log.Printf("#[%d messages received]", len(msgs))
	_form := *outform
	for mi := range msgs {
		err = q.DeleteMessage(id, msgs[mi])
		if err != nil {
			log.Printf("Couldn't delete message, not displaying (%v)", err)
			continue
		}
		switch _form {
		case "text":
			fmt.Printf("MessageID\t%s\n", msgs[mi].MessageId.String())
			fmt.Printf("ReceiptHandle\t%s\n", msgs[mi].ReceiptHandle)
			fmt.Printf("MessageBody\t%s\n", string(msgs[mi].Body))
		case "shell":
			// TODO: Escape these properly.
			fmt.Printf("export SQSMessage%dId=\"%s\";\n", mi, msgs[mi].MessageId.String())
			fmt.Printf("export SQSMessage%dReceipt=\"%s\";\n", mi, msgs[mi].ReceiptHandle)
			fmt.Printf("export SQSMessage%dBody=\"%s\";\n", mi, http.URLEscape(string(msgs[mi].Body)))
		case "raw":
			os.Stdout.Write(msgs[mi].Body)
		}
	}
	if _form == "json" {
		enc := json.NewEncoder(os.Stdout)
		err := enc.Encode(msgs)
		if err != nil {
			log.Fatalf("Error decoding messages: %v", err)
		}
	}
}
Exemplo n.º 28
0
func main() {
	dec := json.NewDecoder(os.Stdin)
	enc := json.NewEncoder(os.Stdout)
	for {
		var v map[string]interface{}
		if err := dec.Decode(&v); err != nil {
			log.Println(err)
			return
		}
		for k := range v {
			if k != "Name" {
				v[k] = nil, false
			}
		}
		if err := enc.Encode(&v); err != nil {
			log.Println(err)
		}
	}
}
Exemplo n.º 29
0
// escapeForJSON will turn a []byte into properly escaped JSON substring.
func escapeForJSON(args ...interface{}) (string, os.Error) {
	// Ensure there is only one argument given
	if len(args) != 1 {
		return "", fmt.Errorf("escapeForJSON: Wrong number of arguments")
	}

	// Converts the given []byte into a JSON encoded string (that's contained in e)
	buf := bytes.NewBuffer(nil)
	e := json.NewEncoder(buf)
	e.Encode(args)

	// Cast to string, and removing preceeding opening "["
	s := strings.TrimLeft(string(buf.Bytes()), "[")
	// Trim down 2 (???) characters to remove trailing closing "]
	s = s[:len(s)-2]

	// Return the string, with no errors
	return s, nil
}
Exemplo n.º 30
0
func serveDirectory(fn string, w http.ResponseWriter, r *http.Request) {
	defer func() {
		if err, ok := recover().(os.Error); ok {
			http.Error(w, err.String(), http.StatusInternalServerError)
		}
	}()
	d, err := os.Open(fn)
	if err != nil {
		panic(err)
	}
	files, err := d.Readdir(-1)
	if err != nil {
		panic(err)
	}
	j := json.NewEncoder(w)
	if err := j.Encode(files); err != nil {
		panic(err)
	}
}