Building microservices using Golang and MongoDB

Source: Internet
Author: User
Tags findone

Building microservices using Golang and MongoDB

Image

Converted to version based on Umermansoor GitHub Python version of micro-service Golang
A total of 4 micro-services

    • Movie Service: Is the basic information about the film, title, rating, etc.
    • Showtimes Service: Information about the time of the movie release
    • Booking Service: Information about subscriptions to movies
    • User Service: Information for users

SOURCE Github

Requirements

    • Golang
    • Mux
    • Mongodb

APIs and documentation

Each service is independent of each other, separate routes and separate databases, the communication between services is through HTTP JSON , the return result of each service API is also JSON type, can refer to using Golang and MongoDB building RESTful API, Extract the common things between services, independent of service, for service invocation

    • The returned result is encapsulated

helper/utils.go

func ResponseWithJson(w http.ResponseWriter, code int, payload interface{}) {    response, _ := json.Marshal(payload)    w.Header().Set("Content-Type", "application/json")    w.WriteHeader(code)    w.Write(response)}
    • Basic Data Entity

models/models.go

  type User struct {Id string ' Bson: ' _id ' json: ' Id ' ' name ' string ' Bson: ' name ' JSON: ' name ' '}type Movie St ruct {ID string ' Bson: ' _id ' JSON: ' id ' ' title string ' Bson: ' title ' JSON: ' title ' ' Rating float32 ' BSO   N: "rating" JSON: "rating" ' director string ' Bson: "Director" JSON: "Director" '}type showtimes struct {Id string  ' Bson: ' _id ' JSON: ' id ' ' Date string ' Bson: ' Date ' JSON: ' Date ' ' Movies []string ' Bson: ' Movies ' json: ' Movies '}type Booking struct {id string ' Bson: ' _id ' JSON: ' id ' ' name ' string ' Bson: ' name ' JSON: ' name ' ' Books []book Info ' Bson: "Books" JSON: "Books" '}type BookInfo struct {date string ' Bson: "Date" JSON: "Date" ' Movies []string ' B Son: "Movies" JSON: "Movies" '}type Result struct {name string ' JSON: ' name ' ' Books []resultinfo ' JSON: ' Books '} Type resultinfo struct {date string ' JSON: ' Date ' ' Movies []movie ' JSON: ' Movies ' '}  
    • About the encapsulation of databases

dao/db.go, please refer to the package of MgO-based operations on MongoDB.

func Insert(db, collection string, docs ...interface{}) error {    ms, c := connect(db, collection)    defer ms.Close()    return c.Insert(docs...)}func FindOne(db, collection string, query, selector, result interface{}) error {    ms, c := connect(db, collection)    defer ms.Close()    return c.Find(query).Select(selector).One(result)}...

Service

Specific logical references for each service use Golang and MongoDB to build RESTful APIs

    • User Service (Port 8000)
    • Movie Service (Port 8001)
    • Showtimes Service (Port 8002)
    • Booking Service (Port 8003)

Service communication

When you query the movie information of a user's subscription, you need to first query the user through the User Service service, according to the user name by Booking Service querying the user's subscription information, and then through the Movie Service service to query the corresponding movie information, are through the HTTP communication

Params: = Mux. Vars (r) Name: = params["name"] var user models. User If err: = DAO. FindOne (DB, Collection, Bson. m{"_id": name}, nil, &user); Err! = Nil {helper. Responsewithjson (W, http. Statusbadrequest, "Invalid Request") return} res, err: = http. Get ("http://127.0.0.1:8003/booking/" + name) If Err! = Nil {helper. Responsewithjson (W, http. Statusbadrequest, "Invalid request by name" +name) return} defer res. Body.close () result, err: = Ioutil. ReadAll (Res. Body) If err! = Nil {helper. Responsewithjson (W, http. Statusbadrequest, "Invalid request of booking by name" +name) return} var booking models. Booking var resresult models. Result resresult.name = Name var resinfo models. Resultinfo If err: = json. Unmarshal (result, &booking); Err = = Nil {for _, Book: = Range booking. Books {resinfo.date = book. Date for _, Movie: = Range book. Movies {res, err: = HttP.get ("http://127.0.0.1:8001/movies/" + movie) if Err = = Nil {result, err: = Ioutil. ReadAll (Res. Body) If Err = = nil {var movie models. Movie If err: = json. Unmarshal (result, &movie);                    Err = = Nil {resinfo.movies = append (Resinfo.movies, Movie)} }}} resresult.books = Append (Resresult.books, resinfo)} Hel Per. Responsewithjson (W, http. Statusok, Resresult)} else {helper. Responsewithjson (W, http. Statusbadrequest, "Invalid Request")}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.