Skip to content

Instantly share code, notes, and snippets.

@ydnar
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ydnar/8e513839808dc206bf42 to your computer and use it in GitHub Desktop.
Save ydnar/8e513839808dc206bf42 to your computer and use it in GitHub Desktop.
V8 JavaScript middleware for Go (golang)
package main
import (
"fmt"
"net/http"
"os"
"reflect"
v8 "github.com/idada/v8.go"
"github.com/nbio/hitch"
)
func main() {
h := hitch.New()
h.Use(Logger)
h.Use(Pushrod)
h.Get("/*extra", http.HandlerFunc(Handler))
port := os.Getenv("PORT")
if port == "" {
port = "8001"
}
http.ListenAndServe("127.0.0.1:"+port, h.Handler())
}
func Handler(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintf(w, "%s %s\n", req.Method, req.URL.Path)
}
func Logger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
fmt.Printf("%s %s\n", req.Method, req.URL.String())
next.ServeHTTP(w, req)
})
}
type Request struct {
Path string `js-field:"path"`
}
func Pushrod(next http.Handler) http.Handler {
engine := v8.NewEngine()
global := engine.NewObjectTemplate()
global.Bind("Request", Request{})
script := engine.Compile([]byte(`
"JavaScript says: " + request.path
`), nil)
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
context := engine.NewContext(global)
context.Scope(func(cs v8.ContextScope) {
r := &Request{
Path: req.URL.Path,
}
cs.Global().SetProperty("request", engine.GoValueToJsValue(reflect.ValueOf(r)))
result := cs.Run(script)
fmt.Println(result.ToString())
})
next.ServeHTTP(w, req)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment