I'm actually learning go, following some tutorial as this one to build an Resftul API app.
First time Using Go and mongoDB, I don't understand well, how to get specific key in certain document of my collection.
Actually I have this object model :
type Numobject struct {
ID bson.ObjectId `bson:"_id" json:"id"`
Text string `bson:"text" json:"text"`
Number int `bson:"number" json:"number"`
Found bool `bson:"found" json:"found"`
Type string `bson:"type" json:"type"`
}
And I can have a specific object by ID with this function :
// Find Object by ID
func (m *NumObjectDAO) FindByNumber(id string) (Numobject, error) {
var numObject Numobject
err := db.C(COLLECTION).FindId(bson.ObjectIdHex(id)).One(&numObject)
return numObject, err
}
I call my method in main.go as follow
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
"gopkg.in/mgo.v2/bson"
. "github.com/sandaleRaclette/03-coddingChallenge/config"
. "github.com/sandaleRaclette/03-coddingChallenge/dao"
. "github.com/sandaleRaclette/03-coddingChallenge/models"
)
// Save the configuration of mongodatabase (localhost and which db use) in Config array
var config = Config{}
var dao = NumObjectDAO{}
// GET list of all objects
func AllObjectsEndPoint(w http.ResponseWriter, r *http.Request) {
movies, err := dao.FindAll()
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
respondWithJson(w, http.StatusOK, movies)
}
// GET an Object by its ID
func FindObjectEndpoint(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
numObject, err := dao.FindByNumber(params["number"])
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid Object ID")
return
}
respondWithJson(w, http.StatusOK, numObject)
}
// Respond Methods
func respondWithError(w http.ResponseWriter, code int, msg string) {
respondWithJson(w, code, map[string]string{"error": msg})
}
func respondWithJson(w http.ResponseWriter, code int, payload interface{}) {
response, _ := json.Marshal(payload)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}
// Parse the configuration file 'config.toml', and establish a connection to DB
func init() {
config.Read()
dao.Server = config.Server
dao.Database = config.Database
dao.Connect()
}
// Define HTTP request routes and define the differents endpoints
func main() {
r := mux.NewRouter()
r.HandleFunc("/api/v1/trivia", AllObjectsEndPoint).Methods("GET")
r.HandleFunc("/api/v1/trivia/{number}", FindObjectEndpoint).Methods("GET")
if err := http.ListenAndServe(":3000", r); err != nil {
log.Fatal(err)
}
}
There is other methods than getting an object by ID? How can I get an object with a specific key as Number or Type following my model ?
I want to obtain something like this when I GET "/api/v1/trivia/45000000" :
{
"id": "5aa554c89d63b0d3580449a5",
"text": "45000000 is the number of turkeys Americans eat at Thanksgiving annually.",
"number": 45000000,
"found": true,
"type": "trivia"
}
I'm actually looking here for some answers but I have some difficulties with query... If someone can give me beginner explanation...