Skip to content

Instantly share code, notes, and snippets.

@luchoching
Last active July 31, 2018 12:47
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luchoching/95f8380f8fc6656b838f to your computer and use it in GitHub Desktop.
Save luchoching/95f8380f8fc6656b838f to your computer and use it in GitHub Desktop.
Golang mgo REST json example
package main
import (
"encoding/json"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"net/http"
)
type Person struct {
Id bson.ObjectId `json:"id" bson:"_id,omitempty"`
Name string `json:"name"`
Phone string `json:"phone"`
}
type Server struct {
session *mgo.Session
}
func NewServer() (*Server, error) {
session, err := mgo.Dial("localhost")
if err != nil {
return nil, err
}
return &Server{session: session}, nil
}
func (s *Server) Close() {
s.session.Close()
}
func (s *Server) personList(w http.ResponseWriter, r *http.Request) {
session := s.session.Copy()
defer session.Close()
result := []Person{}
c := session.DB("test").C("people")
err := c.Find(bson.M{}).All(&result)
if err != nil {
panic(err)
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
j, _ := json.Marshal(result)
w.Write(j)
}
func main() {
srv, err := NewServer()
if err != nil {
panic(err)
}
defer srv.Close()
http.HandleFunc("/people", srv.personList)
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment