我正在编写一个API,该API对OSMR服务器执行查询并检索一些数据,尝试将此数据转换为JSON并在我的API中返回它,一切工作几乎正常,但是结果字符串中的数值不是数值,而是用字符“{}”替换。我不知道发生了什么,我已经研究了这个问题一个小时
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"time"
"log"
"bytes"
"github.com/stretchr/objx"
"github.com/go-martini/martini"
)
func PrettyJson(data interface{}) (string) {
buffer := new(bytes.Buffer)
encoder := json.NewEncoder(buffer)
encoder.SetIndent("", " ")
err := encoder.Encode(data)
if err != nil {
return ""
}
return buffer.String()
}
func main() {
app := martini.Classic()
app.Get("/", func() string {
return "/"
})
app.Get("/routes", func(req *http.Request, res http.ResponseWriter) string {
query, err := url.ParseQuery(req.URL.RawQuery)
if err != nil {
log.Println(err)
}
var client = &http.Client{Timeout: 100 * time.Second}
if v1, v2 := query["src"], query["dst"]; v1 != nil && v2 != nil {
var routes_array []map[string]interface{}
for _, destination := range query["dst"] {
request_url := fmt.Sprintf("http://router.project-osrm.org/route/v1/driving/%s;%s?overview=false", query["src"][0], destination)
response, err := client.Get(request_url)
if err != nil {
log.Fatal(err)
return "{\"message\": \"internal server error\"}"
}
buf := new(bytes.Buffer)
buf.ReadFrom(response.Body)
newStr := buf.String()
document, _ := objx.FromJSON(newStr)
route := map[string]interface{}{
"destination": destination,
"distance": document.Get("routes[0].distance"),
"duration": document.Get("routes[0].duration"),
}
routes_array = append(routes_array, route)
}
}
函数式编程
相关分类