Read the input into a buffer so it can be Unmarshal'ed twice

This commit is contained in:
Kevin Keogh
2017-09-15 12:46:43 -04:00
parent 5a169915e7
commit 1daa63ab11

View File

@@ -3,6 +3,7 @@ package main
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"net/http" "net/http"
) )
@@ -11,24 +12,22 @@ import (
func index(w http.ResponseWriter, r *http.Request) { func index(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" { if r.Method == "POST" {
mcOpt := &Option{} body, err := ioutil.ReadAll(r.Body)
bsOpt := &Option{}
err := json.NewDecoder(r.Body).Decode(&mcOpt)
if err != nil { if err != nil {
fmt.Printf("Error: %s\n", err) fmt.Printf("Error: %s\n", err)
} }
var bsOpt, mcOpt Option
json.Unmarshal(body, &bsOpt)
json.Unmarshal(body, &mcOpt)
mcOpt.PriceMonteCarlo() mcOpt.PriceMonteCarlo()
options := make(map[string]Option) options := make(map[string]Option)
options["MonteCarlo"] = *mcOpt options["MonteCarlo"] = mcOpt
options["BlackScholes"] = *bsOpt options["ClosedForm"] = bsOpt
json.NewEncoder(w).Encode(options) json.NewEncoder(w).Encode(options)
if err != nil {
fmt.Printf("Error: %v\n", err)
}
} else if r.Method == "GET" { } else if r.Method == "GET" {
fmt.Fprintf(w, "Hello go!") // To be updated fmt.Fprintf(w, "Hello go!") // To be updated
@@ -36,7 +35,6 @@ func index(w http.ResponseWriter, r *http.Request) {
} }
func main() { func main() {
http.HandleFunc("/", index) http.HandleFunc("/", index)
http.ListenAndServe(":8080", nil) http.ListenAndServe(":8080", nil)