How to display HTML / JSON / XML dynamically in golang with martini?

I am trying to create a simple REST API server on golang site that serves HTML, JSON, or XML format of the same date as requested by the client. I can not understand. Hope I'm not doing anything stupid.

code:

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()

}

      

Result: I am requesting JSON and I just get the string

$ 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>

      

+3


source to share


1 answer


With some trial and error, I figured it out, however, I am still struggling to get it to work with the routing group. If I ever figure this out, I'll update this answer. Hope this helps.



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()

}

      

+1


source







All Articles