本文整理匯總了Golang中json.NewEncoder函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewEncoder函數的具體用法?Golang NewEncoder怎麽用?Golang NewEncoder使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NewEncoder函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Get
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()
}
示例2: OutputTo
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)
}
示例3: OutputTo
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)
}
示例4: Encode
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)
}
示例5: output
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
}
示例6: postPosition
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)
}
示例7: main
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()
}
}
示例8: ShortenURL
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
}
示例9: main
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")
}
示例10: CheckUidHandler
/* 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
}
示例11: OutputTo
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)
}
示例12: ServeHTTP
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)
}
示例13: NewClientCodec
// 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),
}
}
示例14: NewServerCodec
// 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),
}
}
示例15: serialize
// 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
}