Last active
November 28, 2018 01:02
-
-
Save ox/d415c5289657faa085e7c810422b37dd to your computer and use it in GitHub Desktop.
Using libv8 with Go to recreate Cloudflare Edge Workers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"time" | |
"net/http" | |
"context" | |
"encoding/json" | |
"github.com/gorilla/mux" | |
"github.com/augustoroman/v8" | |
) | |
func CreateSandbox(next http.Handler) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
// make a new isolate and context for this request | |
isolate := v8.NewIsolate() | |
v8ctx := isolate.NewContext() | |
ctx := context.WithValue(r.Context(), "v8ctx", v8ctx) | |
// Serve the request | |
start := time.Now() | |
next.ServeHTTP(w, r.WithContext(ctx)) | |
// Print how long it took to respond, and resources used | |
heapStatistics := isolate.GetHeapStatistics() | |
log.Printf("%v took %v, %v bytes", r.URL.String(), time.Now().Sub(start), heapStatistics.MallocedMemory) | |
v8ctx.Terminate() | |
}) | |
} | |
func Add(w http.ResponseWriter, req *http.Request) { | |
if ctx := req.Context().Value("v8ctx"); ctx != nil { | |
decoder := json.NewDecoder(req.Body) | |
var components struct{ | |
A int | |
B int | |
} | |
err := decoder.Decode(&components) | |
if err != nil { | |
w.WriteHeader(http.StatusInternalServerError) | |
w.Write([]byte("Could not decode JSON request.")) | |
return | |
} | |
res, _ := ctx.(*v8.Context).Eval(fmt.Sprintf("%v + %v", components.A, components.B), "compute.js") | |
w.Write([]byte(res.String())) | |
} else { | |
w.WriteHeader(http.StatusInternalServerError) | |
w.Write([]byte("Could not grab V8 Context")) | |
} | |
} | |
func main() { | |
r := mux.NewRouter() | |
r.Use(CreateSandbox) | |
r.HandleFunc("/add", Add) | |
http.Handle("/", r) | |
log.Println("Listening on localhost:9999") | |
if err := http.ListenAndServe(":9999", nil); err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment