我试图在 golang 站点中有一个简单的 REST API 服务器,它提供与客户端请求的日期相同的 HTML、JSON 或 XML 格式。我无法弄清楚。我希望我没有做傻事。
代码:
package main
import (
"github.com/go-martini/martini"
"github.com/martini-contrib/render"
)
type Ticket struct {
Number int `json:"number"`
Description string `json:"description"`
State string `json:"state"`
}
func dummyStatus() Ticket {
ticket := Ticket{
Number: 2345,
Description: "A dummy customer ticket",
State: "resolved",
}
return ticket
}
// http://localhost:3000/status/id:1
func ReadStatus(r render.Render, params martini.Params) Ticket {
// read from DB
return dummyStatus()
}
func WriteStatus(params martini.Params) Ticket {
// write to DB
return dummyStatus()
}
func main() {
m := martini.Classic()
m.Use(render.Renderer())
m.Group("/status", func(r martini.Router) {
r.Get("/:id", ReadStatus)
r.Post("/:id", WriteStatus)
})
m.Run()
}
结果:我请求 JSON,我只收到一个字符串
$ curl -i -H "Accept: application/json" -H "Content-Type:application/json" -X GET http://localhost:3000/status/id:12345
HTTP/1.1 200 OK
Date: Wed, 24 Dec 2014 20:01:32 GMT
Content-Length: 19
Content-Type: text/plain; charset=utf-8
<main.Ticket Value>