3

I am trying to have a simple REST API server in golang site which serves HTML, JSON or XML format of the same date as requested by client. I am not able to figure out. I hope I am not doing something silly.

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 request for JSON and I just receive a 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>
FlowRaja
  • 677
  • 3
  • 6
  • 15

1 Answers1

2

With some trial and error, I figured this out, however, I am still struggling to make it work with routing group. If I ever figure that out, I will 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()

}
FlowRaja
  • 677
  • 3
  • 6
  • 15
  • Oh I forgot to mention the second limitation I have with this code ... it does not dynamically change the format based on the request. hardcoded JSON responses for now. :-( – FlowRaja Dec 25 '14 at 03:18
  • I've had to perform a similar task where the output is JSON by default and then XML as well. I am doing this just with a secondary route for now that executes a method against my data to render it as XML and then r.Data(200, []byte(xmlstring)) – shat Jan 22 '15 at 22:55