Skip to content

Instantly share code, notes, and snippets.

@rippinrobr
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rippinrobr/9122011 to your computer and use it in GitHub Desktop.
Save rippinrobr/9122011 to your computer and use it in GitHub Desktop.
The code for the beginning of the second post
package main
import (
"github.com/codegangsta/martini"
)
func main() {
m := martini.Classic()
m.Get("/attributes/:resource", getAttributes )
m.Run()
}
package main
import (
"net/http"
"strings"
"encoding/json"
"github.com/codegangsta/martini"
)
type attribute struct {
Id string `json:"id"`
Name string `json:"name"`
DataType string `json:"type"`
Description string `json:"description"`
Required bool `json:"required"`
}
type resourceAttributes struct {
ResourceName string `json: "resourceName"`
Attributes []attribute `json: "attributes"`
}
type errorMsg struct {
Msg string `json:"msg"`
}
type jsonConvertible interface {}
func jsonString( obj jsonConvertible ) (s string) {
jsonObj, err := json.Marshal( obj )
if err != nil {
s = ""
} else {
s = string( jsonObj )
}
return
}
// Handlers start here
func createAttribute( params martini.Params, writer http.ResponseWriter ) (int, string) {
resource := strings.ToLower( params["resource"] )
writer.Header().Set("Content-Type", "application/json")
return http.StatusOK, "Pseudo Create assigned to " + resource
}
func getAttributes( params martini.Params, writer http.ResponseWriter ) (int, string) {
resource := strings.ToLower( params["resource"] )
writer.Header().Set("Content-Type", "application/json")
if resource == "tv" {
resourceAttrs := resourceAttributes{"tv", make([]attribute, 1)}
resourceAttrs.Attributes[0] = attribute{"", "Location","string", "What facility is the TV located in.", true}
return http.StatusOK, jsonString( resourceAttrs )
} else {
return http.StatusNotFound, jsonString( errorMsg{"Resource not found: " + resource} )
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment