使用golang

时间:2017-10-22 23:10:02

标签: json rest go

这是我的第一个去项目。我想要做的就是在我的服务器上读取一个file.json,然后通过REST API将其提供给其他人。但是我收到了错误。这是我到目前为止所拥有的。

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
}

当我运行go build; ./sampleproject时,请转到http://localhost:8000/detail的网络浏览器,收到错误消息:

  

无效字符'f'正在寻找对象键字符串的开头   映射[]

我尝试了一些元帅方法,但他们都给了我不同的错误。我只需要一个工作实例来研究,以便更好地理解这一切是如何运作的。

我还应该提到file.json没有固定的架构。它可以随时变化,以获得随机数据集。

如何解决错误无效字符f消息并让我的file.json在http://localhost:8000/detail呈现?

1 个答案:

答案 0 :(得分:0)

正如cerise所提到的,它只是JSON文件中的格式错误。必须引用所有属性。

然后其余的代码工作