This is my first go project. All I want to do is read a file.json on my server, then make it available to others via a REST API. But I'm getting errors. Here's what I have so far.
main.go
package main
import (
"encoding/json"
"github.com/gorilla/mux"
"log"
"net/http"
"io/ioutil"
"fmt"
)
func GetDetail(w http.ResponseWriter, r *http.Request) {
b,_ := ioutil.ReadFile("file.json");
rawIn := json.RawMessage(string(b))
var objmap map[string]*json.RawMessage
err := json.Unmarshal(rawIn, &objmap)
if err != nil {
fmt.Println(err)
}
fmt.Println(objmap)
json.NewEncoder(w).Encode(objmap)
}
func main() {
router := mux.NewRouter()
router.HandleFunc("/detail", GetDetail).Methods("GET")
log.Fatal(http.ListenAndServe(":8000", router))
}
file.json
{
favourite_color:"blue",
attribute:{density:23,allergy:"peanuts",locations:["USA","Canada","Jamaica"]},
manufacture_year:1998
}
When I run go build; ./sampleproject
, then go to my web browser at http://localhost:8000/detail
, I get the error message:
invalid character 'f' looking for beginning of object key string map[]
I've tried a few marshal methods, but they all give me different errors. I just need a working example to study from to better understand how all this works.
I should also mention that file.json does not have a fixed schema. It can change drastically at any minute to have a random set of data.
How do I get around the error invalid character f message and get my file.json to render at http://localhost:8000/detail
?