3

我试图在 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>
4

1 回答 1

2

经过反复试验,我发现了这一点,但是,我仍在努力使其与路由组一起使用。如果我弄清楚了,我会更新这个答案。希望这可以帮助。

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 ReadStatus(p martini.Params) Ticket {

    ticket := Ticket{
        Number:      645,
        Description: "A dummy customer ticket " + p["id"],
        State:       "resolved",
    }
    return ticket
}

func main() {

    m := martini.Classic()
    m.Use(render.Renderer())

    m.Get("/status/:id", func(r render.Render, params martini.Params) { r.JSON(200, ReadStatus(params)) })

    m.Run()

}
于 2014-12-25T03:01:45.353 回答