Procházet zdrojové kódy

feature(render): Add json rending supports.

- move Send from server to rex (top level).
tags/v0.9.0
jimzhan před 9 roky
rodič
revize
f3174a2113
2 změnil soubory, kde provedl 22 přidání a 18 odebrání
  1. +22
    -0
      rex.go
  2. +0
    -18
      server.go

+ 22
- 0
rex.go Zobrazit soubor

@@ -1,6 +1,9 @@
package rex

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

"github.com/goanywhere/env"
@@ -10,6 +13,25 @@ import (
// Shortcut for string based map.
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() {
var basedir = fs.Getcd(2)
env.Set("basedir", basedir)

+ 0
- 18
server.go Zobrazit soubor

@@ -1,8 +1,6 @@
package rex

import (
"bytes"
"encoding/json"
"flag"
"fmt"
"net/http"
@@ -184,22 +182,6 @@ func (self *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
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.
func (self *server) Run() {
runtime.GOMAXPROCS(maxprocs)

Načítá se…
Zrušit
Uložit