美文网首页Golang 学习笔记
Build RESTful API in Go and Mong

Build RESTful API in Go and Mong

作者: 与蟒唯舞 | 来源:发表于2018-09-29 15:36 被阅读14次

GitHub:https://github.com/happy-python/go_rest_mongo

在本教程中,我将说明如何在 Go 和 MongoDB 中构建自己的 RESTful API。

项目结构
API 规范
安装依赖
go get github.com/BurntSushi/toml gopkg.in/mgo.v2 github.com/gorilla/mux
  • toml:解析配置文件
  • mux:路由映射
  • mgo:MongoDB 驱动
定义模型
package models

import "gopkg.in/mgo.v2/bson"

type Movie struct {
    ID          bson.ObjectId `bson:"_id" json:"id"`
    Name        string        `bson:"name" json:"name"`
    CoverImage  string        `bson:"cover_image" json:"cover_image"`
    Description string        `bson:"description" json:"description"`
}
数据访问对象
package dao

import (
    . "go_rest_mongo/models"
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
    "log"
)

var db *mgo.Database

const (
    COLLECTION = "movies"
)

type MoviesDAO struct {
    Server   string
    Database string
}

func (m *MoviesDAO) Connect() {
    session, err := mgo.Dial(m.Server)
    if err != nil {
        log.Fatal(err)
    }
    db = session.DB(m.Database)
}

// Find list of movies
func (m *MoviesDAO) FindAll() ([]Movie, error) {
    var movies []Movie
    err := db.C(COLLECTION).Find(nil).All(&movies)
    return movies, err
}

// Find a movie by its id
func (m *MoviesDAO) FindById(id string) (Movie, error) {
    var movie Movie
    err := db.C(COLLECTION).FindId(bson.ObjectIdHex(id)).One(&movie)
    return movie, err
}

// Insert a movie into database
func (m *MoviesDAO) Insert(movie Movie) error {
    err := db.C(COLLECTION).Insert(&movie)
    return err
}

// Delete an existing movie
func (m *MoviesDAO) Delete(movie Movie) error {
    err := db.C(COLLECTION).Remove(&movie)
    return err
}

// Update an existing movie
func (m *MoviesDAO) Update(movie Movie) error {
    err := db.C(COLLECTION).UpdateId(movie.ID, &movie)
    return err
}
编写 API
package main

import (
    "encoding/json"
    "github.com/gorilla/mux"
    . "go_rest_mongo/config"
    . "go_rest_mongo/dao"
    . "go_rest_mongo/models"
    utils "go_rest_mongo/utils"
    "gopkg.in/mgo.v2/bson"
    "log"
    "net/http"
)

var config = Config{}
var dao = MoviesDAO{}

// 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()
}

// GET list of movies
func AllMoviesEndPoint(w http.ResponseWriter, req *http.Request) {
    movies, err := dao.FindAll()
    if err != nil {
        utils.RespondWithError(w, http.StatusInternalServerError, err.Error())
        return
    }
    utils.RespondWithJson(w, http.StatusCreated, movies)
}

// GET a movie by its ID
func FindMovieEndpoint(w http.ResponseWriter, req *http.Request) {
    params := mux.Vars(req)
    movie, err := dao.FindById(params["id"])

    if err != nil {
        utils.RespondWithError(w, http.StatusBadRequest, "Invalid Movie ID")
        return
    }
    utils.RespondWithJson(w, http.StatusOK, movie)

}

// POST a new movie
func CreateMovieEndpoint(w http.ResponseWriter, req *http.Request) {
    defer req.Body.Close()

    var movie Movie
    if err := json.NewDecoder(req.Body).Decode(&movie); err != nil {
        utils.RespondWithError(w, http.StatusBadRequest, "Invalid request payload")
        return
    }

    movie.ID = bson.NewObjectId()
    if err := dao.Insert(movie); err != nil {
        utils.RespondWithError(w, http.StatusInternalServerError, err.Error())
        return
    }
    utils.RespondWithJson(w, http.StatusCreated, movie)
}

// PUT update an existing movie
func UpdateMovieEndPoint(w http.ResponseWriter, req *http.Request) {
    defer req.Body.Close()

    var movie Movie
    if err := json.NewDecoder(req.Body).Decode(&movie); err != nil {
        utils.RespondWithError(w, http.StatusBadRequest, "Invalid request payload")
        return
    }

    if err := dao.Update(movie); err != nil {
        utils.RespondWithError(w, http.StatusInternalServerError, err.Error())
        return
    }
    utils.RespondWithJson(w, http.StatusOK, map[string]string{"result": "success"})
}

// DELETE an existing movie
func DeleteMovieEndPoint(w http.ResponseWriter, req *http.Request) {
    defer req.Body.Close()

    var movie Movie
    if err := json.NewDecoder(req.Body).Decode(&movie); err != nil {
        utils.RespondWithError(w, http.StatusBadRequest, "Invalid request payload")
        return
    }

    if err := dao.Delete(movie); err != nil {
        utils.RespondWithError(w, http.StatusInternalServerError, err.Error())
        return
    }
    utils.RespondWithJson(w, http.StatusOK, map[string]string{"result": "success"})
}

// Define HTTP request routes
func main() {
    r := mux.NewRouter()
    r.HandleFunc("/movies", AllMoviesEndPoint).Methods("GET")
    r.HandleFunc("/movies", CreateMovieEndpoint).Methods("POST")
    r.HandleFunc("/movies/{id}", FindMovieEndpoint).Methods("GET")
    r.HandleFunc("/movies", UpdateMovieEndPoint).Methods("PUT")
    r.HandleFunc("/movies", DeleteMovieEndPoint).Methods("DELETE")

    if err := http.ListenAndServe(":3000", r); err != nil {
        log.Fatal(err)
    }
}

原文地址:https://hackernoon.com/build-restful-api-in-go-and-mongodb-5e7f2ec4be94

相关文章

网友评论

    本文标题:Build RESTful API in Go and Mong

    本文链接:https://www.haomeiwen.com/subject/xifboftx.html