示例#1
0
func (c *InterfaceController) Get(w http.ResponseWriter, r *http.Request) {
	id := mux.Vars(r)["id"]

	// Validate ObjectId
	if !bson.IsObjectIdHex(id) {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	// Get object id
	oid := bson.ObjectIdHex(id)

	// Initialize empty struct
	s := models.Interface{}

	// Get entry
	if err := c.session.DB(c.database).C("interfaces").FindId(oid).One(&s); err != nil {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	// Embed related data
	if r.URL.Query().Get("embed") == "true" {
		if s.SubnetID != "" {
			// Get subnet
			if err := c.session.DB(c.database).C("subnets").FindId(s.SubnetID).One(&s.Subnet); err != nil {
				w.WriteHeader(http.StatusNotFound)
				return
			}
		}
		// Get Host
		if err := c.session.DB(c.database).C("hosts").FindId(s.HostID).One(&s.Host); err != nil {
			w.WriteHeader(http.StatusNotFound)
			return
		}
	}

	// HATEOAS Links
	hateoas := c.hateoas
	switch strings.ToLower(r.URL.Query().Get("hateoas")) {
	case "true":
		hateoas = true
	case "false":
		hateoas = false
	}
	if hateoas == true {
		links := []models.Link{}

		if s.SubnetID != "" {
			links = append(links, models.Link{
				HRef:   c.baseURI + "/subnets/" + s.SubnetID.Hex(),
				Rel:    "self",
				Method: "GET",
			})
		}

		if s.HostID != "" {
			links = append(links, models.Link{
				HRef:   c.baseURI + "/hosts/" + s.HostID.Hex(),
				Rel:    "self",
				Method: "GET",
			})
		}

		s.Links = &links
	}

	// HATEOAS Links
	if c.hateoas == true || r.URL.Query().Get("hateoas") == "true" {
		s.Links = &[]models.Link{
			models.Link{
				HRef:   c.baseURI + "/subnets/" + s.SubnetID.Hex(),
				Rel:    "self",
				Method: "GET",
			},
			models.Link{
				HRef:   c.baseURI + "/hosts/" + s.HostID.Hex(),
				Rel:    "self",
				Method: "GET",
			},
		}
	}

	// Write content-type, header and payload
	jsonWriter(w, r, s, http.StatusOK, c.envelope)
}