Browse Source

feature(render): Add json rending supports.

- move Send from server to rex (top level).
tags/v0.9.0
jimzhan 9 years ago
parent
commit
f3174a2113
2 changed files with 22 additions and 18 deletions
  1. +22
    -0
      rex.go
  2. +0
    -18
      server.go

+ 22
- 0
rex.go View File

package rex package rex


import ( import (
"bytes"
"encoding/json"
"net/http"
"path" "path"


"github.com/goanywhere/env" "github.com/goanywhere/env"
// Shortcut for string based map. // Shortcut for string based map.
type M map[string]interface{} type M map[string]interface{}


// Sends the HTTP response in JSON.
func Send(w http.ResponseWriter, v interface{}) {
var buffer = new(bytes.Buffer)
defer func() {
buffer.Reset()
}()

w.Header().Set("Content-type", "application/json; charset=utf-8")
if err := json.NewEncoder(buffer).Encode(v); err == nil {
w.Write(buffer.Bytes())
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}

// Renders a view (Pongo) and sends the rendered HTML string to the client.
// Optional parameters: value, local variables for the view.
// func Render(filename string, v ...interface{}) {}

func init() { func init() {
var basedir = fs.Getcd(2) var basedir = fs.Getcd(2)
env.Set("basedir", basedir) env.Set("basedir", basedir)

+ 0
- 18
server.go View File

package rex package rex


import ( import (
"bytes"
"encoding/json"
"flag" "flag"
"fmt" "fmt"
"net/http" "net/http"
self.build().ServeHTTP(w, r) self.build().ServeHTTP(w, r)
} }


// Sends the HTTP response in JSON.
func (self *server) Send(w http.ResponseWriter, v interface{}) {
var buffer = new(bytes.Buffer)

w.Header().Set("Content-type", "application/json; charset=utf-8")
if err := json.NewEncoder(buffer).Encode(v); err == nil {
w.Write(buffer.Bytes())
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}

// Renders a view (Pongo) and sends the rendered HTML string to the client.
// Optional parameters: value, local variables for the view.
// func (self *server) Render(filename string, v ...interface{}) {}

// Run starts the application server to serve incoming requests at the given address. // Run starts the application server to serve incoming requests at the given address.
func (self *server) Run() { func (self *server) Run() {
runtime.GOMAXPROCS(maxprocs) runtime.GOMAXPROCS(maxprocs)

Loading…
Cancel
Save