Skip to content

Instantly share code, notes, and snippets.

@tboerger
Created April 30, 2017 16:22
Show Gist options
  • Save tboerger/48118a3785385096a3fe0f9f7b69b7ea to your computer and use it in GitHub Desktop.
Save tboerger/48118a3785385096a3fe0f9f7b69b7ea to your computer and use it in GitHub Desktop.
Restapi with mgo ang go gin-gonic
I can't seem to findout how to use go gin-gonic to perform CRUD or GET, PUT and POST with MongoDB
Below is my code, please Kindly assist me
package main
import (
//"encoding/json"
"fmt"
"log"
"net/http"
"os"
// "goji.io"
// "goji.io/pat"
"gopkg.in/gin-gonic/gin.v1"
"gopkg.in/mgo.v2"
// "gopkg.in/mgo.v2/bson"
// "github.com/rs/cors"
)
func ErrorWithJSON(w http.ResponseWriter, message string, code int) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(code)
fmt.Fprintf(w, "{message: %q}", message)
}
func ResponseWithJSON(w http.ResponseWriter, json []byte, code int) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(code)
w.Write(json)
}
type Poll struct {
ID string json:"id,omitempty"
Firstname string json:"firstname,omitempty"
Lastname string json:"lastname,omitempty"
Poll string json:"poll,omitempty"
// Address *Address json:"address,omitempty"
}
func main() {
port := os.Getenv("PORT")
if port == "" {
log.Fatal("$PORT must be set")
}
session, err := mgo.Dial("localhost")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
ensureIndex(session)
router := gin.Default()
router.GET("/polls", func(c * gin.Context) {
//c.HTML(http.StatusOK, "polls", nil)
//var polls []Poll
//err := c.Find(bson.M{}).All(&polls)
// **Help Needed Here**
})
router.Run(":" + port)
}
func ensureIndex(s *mgo.Session) {
session := s.Copy()
defer session.Close()
c := session.DB("store").C("polls")
index := mgo.Index{
Key: []string{"id"},
Unique: true,
DropDups: true,
Background: true,
Sparse: true,
}
err := c.EnsureIndex(index)
if err != nil {
panic(err)
}
}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment