본문 바로가기

GoLang

GIN MongoDB Test

/db 요청시 GIN으로 MongoDB의 데이터 값을 출력하기

 

route.go

func (server *serverStruct) SetRoute() bool {
	server.route.GET("/db", handler.PostgreSQLHandler)
    }

라우팅 코드 작성

 

dbHandler.go

package handler

import (
	"context"
	"fmt"
	"log"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"

	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)


type Dog struct {
	ID     primitive.ObjectID
	Name   string
	Family string
	Age    int
	Weight int
}


func PostgreSQLHandler(c *gin.Context) {
	clientOptions1 := options.Client().ApplyURI("mongodb://localhost:27017/local")
    
	client1, err := mongo.NewClient(clientOptions1)
	if err != nil {
		log.Fatal(err)
	}

	err = client1.Connect(context.Background())
	
	collection1 := client1.Database("local").Collection("test")
	// find documents

	doc1 := collection1.FindOne(context.TODO(), bson.M{})
	var dog Dog
	doc1.Decode(&dog)
	fmt.Println(dog)

}

핸들러코드 작성

 

DB에 저장했던 값 출력

'GoLang' 카테고리의 다른 글

GIN 동적 그래프 그리기  (0) 2020.11.20
GIN 그래프 그리기  (0) 2020.11.19
GIN POST TEST2  (0) 2020.11.14
GIN POST 테스트  (0) 2020.11.12
리눅스 서버에 GIN 포팅하기  (0) 2020.11.11