Skip to content

Commit

Permalink
Feat/tamarin eval api (#38)
Browse files Browse the repository at this point in the history
  • Loading branch information
KnockOutEZ committed Jul 7, 2023
1 parent 48e5fea commit 9ac797a
Show file tree
Hide file tree
Showing 4 changed files with 129 additions and 0 deletions.
83 changes: 83 additions & 0 deletions cmd/risor-api/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package main

import (
"context"
"encoding/json"
"flag"
"log"
"net/http"
"time"

"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/risor-io/risor"
"github.com/risor-io/risor/modules/all"
"github.com/risor-io/risor/parser"
)

type Request struct {
Content string `json:"content"`
}

type Response struct {
Result string `json:"result"`
Time float64 `json:"time"`
}

func main() {
var port string
flag.StringVar(&port, "port", "3000", "Define port for the server to listen on")
flag.Parse()

r := chi.NewRouter()
r.Use(middleware.Logger)
r.Post("/execute", func(w http.ResponseWriter, r *http.Request) {
executeHandler(w, r)
})

log.Println("Server started on http://localhost:" + port)
log.Fatal(http.ListenAndServe(":" + port, r))
}

func executeHandler(w http.ResponseWriter, r *http.Request) {
var req Request
var res Response
json.NewDecoder(r.Body).Decode(&req)

input := req.Content
if input == "" {
http.Error(w, "Please provide a code snippet", http.StatusBadRequest)
return
}

ctx := context.Background()
start := time.Now()

result, err := risor.Eval(ctx, string(input),
risor.WithBuiltins(all.Builtins()),
risor.WithDefaultBuiltins(),
risor.WithDefaultModules())
if err != nil {
parserErr, ok := err.(parser.ParserError)
if ok {
http.Error(w, parserErr.FriendlyMessage(), http.StatusInternalServerError)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}

res.Result = result.Inspect()

res.Time = time.Since(start).Seconds()

response, err := json.Marshal(res)
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}

w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
w.Write(response)
}
43 changes: 43 additions & 0 deletions cmd/risor-api/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package main

import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)

func TestExecuteHandler(t *testing.T) {
payload := Request{
Content: "['welcome', 'to', 'risor', '👋'] | strings.join(' ')",
}
payloadBytes, _ := json.Marshal(payload)

req, err := http.NewRequest("POST", "/execute", bytes.NewBuffer(payloadBytes))
if err != nil {
t.Fatal(err)
}

rr := httptest.NewRecorder()

executeHandler(rr, req)

if status := rr.Code; status != http.StatusCreated {
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusCreated)
}

var response Response
if err := json.Unmarshal(rr.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}

expectedResult := "\"welcome to risor 👋\""
if response.Result != expectedResult {
t.Errorf("handler returned unexpected result: got %s want %s", response.Result, expectedResult)
}

if response.Time <= 0 {
t.Errorf("handler returned invalid response time: %f", response.Time)
}
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ require (
github.com/aws/smithy-go v1.13.5 // indirect
github.com/containerd/console v1.0.3 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/go-chi/chi/v5 v5.0.8
github.com/hashicorp/errwrap v1.0.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,8 @@ github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs=
github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/go-chi/chi/v5 v5.0.8 h1:lD+NLqFcAi1ovnVZpsnObHGW4xb4J8lNmoYVfECH1Y0=
github.com/go-chi/chi/v5 v5.0.8/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/gofrs/uuid v4.4.0+incompatible h1:3qXRTX8/NbyulANqlc0lchS1gqAVxRgsuW1YrTJupqA=
github.com/gofrs/uuid v4.4.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
Expand Down

0 comments on commit 9ac797a

Please sign in to comment.