Files
go-opt-pricer/serve.go

57 lines
1.3 KiB
Go

package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
// index is a function that handles all requests to the main page
// Note that there are two separate returns
func index(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Printf("Error: %s\n", err)
}
var bsOpt, mcOpt Option
json.Unmarshal(body, &bsOpt)
json.Unmarshal(body, &mcOpt)
// Cap the number of simulations at 10M
if bsOpt.Sims > 1e7 || mcOpt.Sims > 1e7 {
bsOpt.Sims = 1e7
mcOpt.Sims = 1e7
}
mcOpt.PriceMonteCarlo()
bsOpt.PriceClosedForm()
// Only send the first 10000 levels, as the data going over
// the wire would otherwise be very significant
mcOpt.Levels = mcOpt.Levels[:1000]
options := make(map[string]Option)
options["MonteCarlo"] = mcOpt
options["ClosedForm"] = bsOpt
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(options)
} else if r.Method == "GET" {
http.ServeFile(w, r, "./templates/index.html")
}
}
func main() {
// Serve index.html
http.HandleFunc("/", index)
// Serve all the assets
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("./templates/assets"))))
http.ListenAndServe(":8080", nil)
}