TECH |
Engadget Japanese |
WindowsノートPCがお得なセール中:Amazon初売り(1月6日まで) |
https://japanese.engadget.com/amazon-pc-070124445.html
|
amazon |
2022-01-03 07:01:24 |
TECH |
Techable(テッカブル) |
AI、宇宙開発、量子コンピューター……。2022年も目が離せない、世界のテックニュース4選を振り返り |
https://techable.jp/archives/170176
|
仮想現実 |
2022-01-03 07:00:13 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
pyfigletの使用可能フォント一覧(プレビュー付) |
https://qiita.com/tommy_aka_jps/items/4cd675e3bea4c2632d4d
|
使用可能フォントの名前を取得するだけならpyfigletlistfontsで出力できるのですが、フォント名見てもどんな形をしているのかさっぱりわからないので、フォント名と表示をセットにした一覧表を作ってみました。 |
2022-01-03 16:56:31 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
Bayes theoremとHMMとViterbi Algorithm 備忘録 |
https://qiita.com/Ihmon/items/7e46e25717a62d8f6a08
|
チュートリアルには各ステップの任意のhiddenstateの確率が出力されているとなっているが、どのようにsumをとってもにならず、本当に確率なのか不明。 |
2022-01-03 16:02:34 |
js |
JavaScriptタグが付けられた新着投稿 - Qiita |
素人なりに本気でJavaScriptでクイズアプリを作ってみた。 |
https://qiita.com/akr_trader/items/32bea9755e8c626e6c23
|
完成はこちらです→ファイナルチェック数学IA条件としては・答えを場所で覚えないため選択肢がランダムで表示されて欲しい・数式も問題なく表示して欲しい・得点を集計し、それに応じた判定文を出す。 |
2022-01-03 16:57:32 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
Rubyでランキング順に出力 |
https://teratail.com/questions/376473?rss=all
|
現在はRubyでファイルを読み取り、血液型の項目の人数をカウントした後に昇順に順位付けをするという問題を行っています。 |
2022-01-03 16:57:34 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
「フォルダの中のcsvを全て読み込む」を複数のフォルダに対してループで行いたい |
https://teratail.com/questions/376472?rss=all
|
「フォルダの中のcsvを全て読み込む」を複数のフォルダに対してループで行いたい前提・実現したいことフォルダの中にあるcsvファイルを全て読み込んで縦積みにして一つのデータフレームに入れます。 |
2022-01-03 16:45:13 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
pycaretのパッケージをGoogle colabで実行する際にエラーが発生してしまう。 |
https://teratail.com/questions/376471?rss=all
|
pycaretのパッケージをGooglecolabで実行する際にエラーが発生してしまう。 |
2022-01-03 16:43:44 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
javascriptでheaderの高さを取得し、bodyのpadding-topの高さを変更したい。 |
https://teratail.com/questions/376470?rss=all
|
前提・実現したいことjavascriptで現在のヘッダーの高さに合わせてbodyのpaddingを変えるものを作っています。 |
2022-01-03 16:36:19 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
【OAuth2】認可コードグラントにおいて、直接アクセストークンを介さず最初に認可コードを介す理由が分かりません |
https://teratail.com/questions/376469?rss=all
|
【OAuth】認可コードグラントにおいて、直接アクセストークンを介さず最初に認可コードを介す理由が分かりませんOAuthを勉強している者です。 |
2022-01-03 16:32:07 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
idを元に都道府県名をfilter関数を使って表示させたい |
https://teratail.com/questions/376468?rss=all
|
|
2022-01-03 16:02:49 |
Ruby |
Rubyタグが付けられた新着投稿 - Qiita |
【JAWSDB設定】HerokuでMysqlを使う |
https://qiita.com/shizimi_50/items/3f0ca56649dc8f968267
|
【JAWSDB設定】HerokuでMysqlを使うJAWSDB設定バージョンrubyrailsmysql前提Herokuへのログイン、及びアプリ作成は完了していることアドオンを追加Herokuの標準のDBはPostgresのため、MySQL使う場合はアドオンの追加が必要になるMySQLのアドオンは知る限りClearDBとJawsDBの二種類あるバージョンの違いにより使い分けるClearDBのMySQLのバージョンは系JawsDBのMySQLのバージョンは系今回は、タイトルにもある通り、JawsDBを利用します。 |
2022-01-03 16:08:38 |
AWS |
AWSタグが付けられた新着投稿 - Qiita |
QuickSight Dashboard のワンクリック埋め込み(1-click embedding)をやってみた |
https://qiita.com/sugimount-a/items/4e44893c4342e88e757b
|
QuickSightDashboardのワンクリック埋め込みclickembeddingをやってみたはじめにQuickSightで作成したダッシュボードを、好きなWebアプリケーションに埋め込むことが出来ます。 |
2022-01-03 16:53:24 |
Git |
Gitタグが付けられた新着投稿 - Qiita |
Githubにpushしたらエラーが出た話 |
https://qiita.com/Hiroto0706/items/e7385058791691c052d7
|
Githubにpushしたらエラーが出た話Githubにpushしたらエラーが出たgithubにpushしたところ、以下のようなエラーが出ました。 |
2022-01-03 16:01:58 |
海外TECH |
DEV Community |
Build a REST API with Golang and MongoDB - Fiber Version |
https://dev.to/hackmamba/build-a-rest-api-with-golang-and-mongodb-fiber-version-4la0
|
Build a REST API with Golang and MongoDB Fiber VersionRepresentational state transfer REST is an architectural pattern that guides an Application programming interface API design and development REST APIs have become the standard of communication between the server part of the product and its client to increase performance scalability simplicity modifiability visibility portability and reliability This post will discuss building a user management application with Golang using the Fiber framework and MongoDB At the end of this tutorial we will learn how to structure a Fiber application build a REST API and persist our data using MongoDB Fiber is an Express inspired HTTP web framework written in Golang with performance and zero memory allocation support Fiber is built on top of Fasthttp an HTTP engine written in Golang MongoDB is a document based database management program used as an alternative to relational databases MongoDB supports working with large sets of distributed data with options to store or retrieve information seamlessly You can find the complete source code in this repository PrerequisitesThe following steps in this post require Golang experience Experience with MongoDB isn t a requirement but it s nice to have We will also be needing the following A MongoDB account to host database Signup is completely free Postman or any API testing application of your choice Let s code Getting StartedTo get started we need to navigate to the desired directory and run the command below in our terminal mkdir fiber mongo api amp amp cd fiber mongo apiThis command creates a fiber mongo api folder and navigates into the project directory Next we need to initialize a Go module to manage project dependencies by running the command below go mod init fiber mongo apiThis command will create a go mod file for tracking project dependencies We proceed to install the required dependencies with go get u github com gofiber fiber v go mongodb org mongo driver mongo github com joho godotenv github com go playground validator vgithub com gofiber fiber v is a framework for building web application go mongodb org mongo driver mongo is a driver for connecting to MongoDB github com joho godotenv is a library for managing environment variable github com go playground validator v is a library for validating structs and fields After installing the required dependencies we might get github com klauspost compress is not in your go mod filego mod tidy error in go mod file To fix this we need to manually install the required package withgo get github com klauspost compress Application Entry PointWith the project dependencies installed we need to create main go file in the root directory and add the snippet below The snippet above does the following Import the required dependencies Initialize a Fiber application using the New function Use the Get function to route to path and an handler function that returns a JSON of Hello from Fiber amp mongoDB fiber Map is a shortcut for map string interface useful for JSON returns Set the application to listen on port Next we can test our application by starting the development server by running the command below in our terminal go run main go Modularization in GolangIt is essential to have a good folder structure for our project Good project structure simplifies how we work with dependencies in our application and makes it easier for us and others to read our codebase To do this we need to create configs controllers models responses and routes folder in our project directory PS The go sum file contains all the dependency checksums and is managed by the go tools We don t have to worry about it configs is for modularizing project configuration filescontrollers is for modularizing application logics models is for modularizing data and database logics responses is for modularizing files describing the response we want our API to give This will become clearer later on routes is for modularizing URL pattern and handler information Setting up MongoDBWith that done we need to log in or sign up into our MongoDB account Click the project dropdown menu and click on the New Project button Enter the golang api as the project name click Next and click Create Project Click on Build a DatabaseSelect Shared as the type of database Click on Create to setup a cluster This might take sometime to setup Next we need to create a user to access the database externally by inputting the Username Password and then clicking on Create User We also need to add our IP address to safely connect to the database by clicking on the Add My Current IP Address button Then click on Finish and Close to save changes On saving the changes we should see a Database Deployments screen as shown below Connecting our application to MongoDBWith the configuration done we need to connect our application with the database created To do this click on the Connect buttonClick on Connect your application change the Driver to Go and the Version as shown below Then click on the copy icon to copy the connection string Setup Environment VariableNext we must modify the copied connection string with the user s password we created earlier and change the database name To do this first we need to create a env file in the root directory and in this file add the snippet below MONGOURI mongodb srv lt YOUR USERNAME HERE gt lt YOUR PASSWORD HERE gt cluster eakf mongodb net myFirstDatabese retryWrites true amp w majoritySample of a properly filled connection string below MONGOURI mongodb srv malomz malomzPassword cluster eakf mongodb net golangDB retryWrites true amp w majorityLoad Environment VariableWith that done we need to create a helper function to load the environment variable using the github com joho godotenv library we installed earlier To do this we need to navigate to the configs folder and in this folder create an env go file and add the snippet below The snippet above does the following Import the required dependencies Create an EnvMongoURI function that checks if the environment variable is correctly loaded and returns the environment variable Connecting to MongoDB To connect to the MongoDB database from our application first we need to navigate to the configs folder and in this folder create a setup go file and add the snippet below The snippet above does the following Import the required dependencies Create a ConnectDB function that first configures the client to use the correct URI and check for errors Secondly we defined a timeout of seconds we wanted to use when trying to connect Thirdly check if there is an error while connecting to the database and cancel the connection if the connecting period exceeds seconds Finally we pinged the database to test our connection and returned the client instance Create a DB variable instance of the ConnectDB This will come in handy when creating collections Create a GetCollection function to retrieve and create collections on the database Next we need to connect to the database when our application startup To do this we need to modify main go as shown below Setup API Route Handler and Response TypeRoute HandlerWith that done we need to create a user route go file inside the routes folder to manage all the user related routes in our application as shown below Next we need to attach the newly created route to the http Server in main go by modifying it as shown below Response TypeNext we need to create a reusable struct to describe our API s response To do this navigate to the responses folder and in this folder create a user response go file and add the snippet below The snippet above creates a UserResponse struct with Status Message and Data property to represent the API response type PS json status json message and json data are known as struct tags Struct tags allow us to attach meta information to corresponding struct properties In other words we use them to reformat the JSON response returned by the API Finally Creating REST API sNext we need a model to represent our application data To do this we need to navigate to the models folder and in this folder create a user model go file and add the snippet below The snippet above does the following Import the required dependencies Create a User struct with required properties We added omitempty and validate required to the struct tag to tell Fiber to ignore empty fields and make the field required respectively Create a User EndpointWith the model setup we can now create a function to create a user To do this we need to navigate to the controllers folder and in this folder create a user controller go file and add the snippet below The snippet above does the following Import the required dependencies Create userCollection and validate variables to create a collection and validate models using the github com go playground validator v library we installed earlier on respectively Create a CreateUser function that returns an error Inside the function we first defined a timeout of seconds when inserting user into the document validating both the request body and required field using the validator library We returned the appropriate message and status code using the UserResponse struct we created earlier Secondly we created a newUser variable inserted it using the userCollection InsertOne function and check for errors if there are any Finally we returned the correct response if the insert was successful Next we need to update user routes go with the route API URL and corresponding controller as shown below Get a User EndpointTo get the details of a user we need to modify user controller go as shown below The snippet above does the following Import the required dependencies Create a GetAUser function that returns an error Inside the function we first defined a timeout of seconds when finding a user in the document a userId variable to get the user s id from the URL parameter and a user variable We converted the userId from a string to a primitive ObjectID type a BSON type MongoDB uses Secondly we searched for the user using the userCollection FindOne pass the objId as a filter and use the Decode attribute method to get the corresponding object Finally we returned the decoded response Next we need to update user routes go with the route API URL and corresponding controller as shown below PS We also passed a userId as a parameter to the URL path The specified parameter must match the one we specified in the controller Edit a User EndpointTo edit a user we need to modify user controller go as shown below The EditAUser function above does the same thing as the CreateUser function However we included an update variable to get updated fields and updated the collection using the userCollection UpdateOne Lastly we searched for the updated user s details and returned the decoded response Next we need to update user routes go with the route API URL and corresponding controller as shown below Delete a User EndpointTo delete a user we need to modify user controller go as shown below The DeleteAUser function follows the previous steps by deleting the matched record using the userCollection DeleteOne We also checked if an item was successfully deleted and returned the appropriate response Next we need to update user routes go with the route API URL and corresponding controller as shown below Get List of Users EndpointTo get the list of users we need to modify user controller go as shown below The GetAllUsers function follows the previous steps by getting the list of users using the userCollection Find We also read the retuned list optimally using the Next attribute method to loop through the returned list of users Next we need to update user routes go with the route API URL and corresponding controller as shown below Complete user controller go Complete user route go With that done we can test our application by starting the development server by running the command below in our terminal go run main go ConclusionThis post discussed how to structure a Fiber application build a REST API and persist our data using MongoDB You may find these resources helpful FiberMongoDB Go DriverGo ValidatorGo Environment Loader |
2022-01-03 07:20:12 |
海外TECH |
DEV Community |
Build a REST API with Golang and MongoDB - Echo Version |
https://dev.to/hackmamba/build-a-rest-api-with-golang-and-mongodb-echo-version-2gdg
|
Build a REST API with Golang and MongoDB Echo VersionRepresentational state transfer REST is an architectural pattern that guides an Application programming interface API design and development REST APIs have become the standard of communication between the server part of the product and its client to increase performance scalability simplicity modifiability visibility portability and reliability This post will discuss building a user management application with Golang using the Echo framework and MongoDB At the end of this tutorial we will learn how to structure an Echo application build a REST API and persist our data using MongoDB Echo is a Golang based HTTP web framework with high performance and extensibility It supports optimized routing middlewares templating data binding and rendering MongoDB is a document based database management program used as an alternative to relational databases MongoDB supports working with large sets of distributed data with options to store or retrieve information seamlessly You can find the complete source code in this repository PrerequisitesThe following steps in this post require Golang experience Experience with MongoDB isn t a requirement but it s nice to have We will also be needing the following A MongoDB account to host database Signup is completely free Postman or any API testing application of your choice Let s code Getting StartedTo get started we need to navigate to the desired directory and run the command below in our terminal mkdir echo mongo api amp amp cd echo mongo apiThis command creates an echo mongo api folder and navigates into the project directory Next we need to initialize a Go module to manage project dependencies by running the command below go mod init echo mongo apiThis command will create a go mod file for tracking project dependencies We proceed to install the required dependencies with go get u github com labstack echo v go mongodb org mongo driver mongo github com joho godotenv github com go playground validator vgithub com labstack echo v is a framework for building web application go mongodb org mongo driver mongo is a driver for connecting to MongoDB github com joho godotenv is a library for managing environment variable github com go playground validator v is a library for validating structs and fields Application Entry PointWith the project dependencies installed we need to create main go file in the root directory and add the snippet below The snippet above does the following Import the required dependencies Initialize an Echo application using the New function Use the Get function to route to path and an handler function that returns a JSON of Hello from Echo amp mongoDB echo Map is a shortcut for map string interface useful for JSON returns Use the Start function to run the application on port Next we can test our application by starting the development server by running the command below in our terminal go run main go Modularization in GolangIt is essential to have a good folder structure for our project Good project structure simplifies how we work with dependencies in our application and makes it easier for us and others to read our codebase To do this we need to create configs controllers models responses and routes folder in our project directory PS The go sum file contains all the dependency checksums and is managed by the go tools We don t have to worry about it configs is for modularizing project configuration filescontrollers is for modularizing application logics models is for modularizing data and database logics responses is for modularizing files describing the response we want our API to give This will become clearer later on routes is for modularizing URL pattern and handler information Setting up MongoDBWith that done we need to log in or sign up into our MongoDB account Click the project dropdown menu and click on the New Project button Enter the golang api as the project name click Next and click Create Project Click on Build a DatabaseSelect Shared as the type of database Click on Create to setup a cluster This might take sometime to setup Next we need to create a user to access the database externally by inputting the Username Password and then clicking on Create User We also need to add our IP address to safely connect to the database by clicking on the Add My Current IP Address button Then click on Finish and Close to save changes On saving the changes we should see a Database Deployments screen as shown below Connecting our application to MongoDBWith the configuration done we need to connect our application with the database created To do this click on the Connect buttonClick on Connect your application change the Driver to Go and the Version as shown below Then click on the copy icon to copy the connection string Setup Environment VariableNext we must modify the copied connection string with the user s password we created earlier and change the database name To do this first we need to create a env file in the root directory and in this file add the snippet below MONGOURI mongodb srv lt YOUR USERNAME HERE gt lt YOUR PASSWORD HERE gt cluster eakf mongodb net myFirstDatabese retryWrites true amp w majoritySample of a properly filled connection string below MONGOURI mongodb srv malomz malomzPassword cluster eakf mongodb net golangDB retryWrites true amp w majorityLoad Environment VariableWith that done we need to create a helper function to load the environment variable using the github com joho godotenv library we installed earlier To do this we need to navigate to the configs folder and in this folder create an env go file and add the snippet below The snippet above does the following Import the required dependencies Create an EnvMongoURI function that checks if the environment variable is correctly loaded and returns the environment variable Connecting to MongoDB To connect to the MongoDB database from our application first we need to navigate to the configs folder and in this folder create a setup go file and add the snippet below The snippet above does the following Import the required dependencies Create a ConnectDB function that first configures the client to use the correct URI and check for errors Secondly we defined a timeout of seconds we wanted to use when trying to connect Thirdly check if there is an error while connecting to the database and cancel the connection if the connecting period exceeds seconds Finally we pinged the database to test our connection and returned the client instance Create a DB variable instance of the ConnectDB This will come in handy when creating collections Create a GetCollection function to retrieve and create collections on the database Next we need to connect to the database when our application startup To do this we need to modify main go as shown below Setup API Route Handler and Response TypeRoute HandlerWith that done we need to create a user route go file inside the routes folder to manage all the user related routes in our application as shown below Next we need to attach the newly created route to the http Server in main go by modifying it as shown below Response TypeNext we need to create a reusable struct to describe our API s response To do this navigate to the responses folder and in this folder create a user response go file and add the snippet below The snippet above creates a UserResponse struct with Status Message and Data property to represent the API response type PS json status json message and json data are known as struct tags Struct tags allow us to attach meta information to corresponding struct properties In other words we use them to reformat the JSON response returned by the API Finally Creating REST API sNext we need a model to represent our application data To do this we need to navigate to the models folder and in this folder create a user model go file and add the snippet below The snippet above does the following Import the required dependencies Create a User struct with required properties We added omitempty and validate required to the struct tag to tell Fiber to ignore empty fields and make the field required respectively Create a User EndpointWith the model setup we can now create a function to create a user To do this we need to navigate to the controllers folder and in this folder create a user controller go file and add the snippet below The snippet above does the following Import the required dependencies Create userCollection and validate variables to create a collection and validate models using the github com go playground validator v library we installed earlier on respectively Create a CreateUser function that returns an error Inside the function we first defined a timeout of seconds when inserting user into the document validating both the request body and required field using the validator library We returned the appropriate message and status code using the UserResponse struct we created earlier Secondly we created a newUser variable inserted it using the userCollection InsertOne function and check for errors if there are any Finally we returned the correct response if the insert was successful Next we need to update user routes go with the route API URL and corresponding controller as shown below Get a User EndpointTo get the details of a user we need to modify user controller go as shown below The snippet above does the following Import the required dependencies Create a GetAUser function that returns an error Inside the function we first defined a timeout of seconds when finding a user in the document a userId variable to get the user s id from the URL parameter and a user variable We converted the userId from a string to a primitive ObjectID type a BSON type MongoDB uses Secondly we searched for the user using the userCollection FindOne pass the objId as a filter and use the Decode attribute method to get the corresponding object Finally we returned the decoded response Next we need to update user routes go with the route API URL and corresponding controller as shown below PS We also passed a userId as a parameter to the URL path The specified parameter must match the one we specified in the controller Edit a User EndpointTo edit a user we need to modify user controller go as shown below The EditAUser function above does the same thing as the CreateUser function However we included an update variable to get updated fields and updated the collection using the userCollection UpdateOne Lastly we searched for the updated user s details and returned the decoded response Next we need to update user routes go with the route API URL and corresponding controller as shown below Delete a User EndpointTo delete a user we need to modify user controller go as shown below The DeleteAUser function follows the previous steps by deleting the matched record using the userCollection DeleteOne We also checked if an item was successfully deleted and returned the appropriate response Next we need to update user routes go with the route API URL and corresponding controller as shown below Get List of Users EndpointTo get the list of users we need to modify user controller go as shown below The GetAllUsers function follows the previous steps by getting the list of users using the userCollection Find We also read the retuned list optimally using the Next attribute method to loop through the returned list of users Next we need to update user routes go with the route API URL and corresponding controller as shown below Complete user controller go Complete user route go With that done we can test our application by starting the development server by running the command below in our terminal go run main go ConclusionThis post discussed how to structure an Echo application build a REST API and persist our data using MongoDB You may find these resources helpful EchoMongoDB Go DriverGo ValidatorGo Environment Loader |
2022-01-03 07:19:19 |
海外TECH |
DEV Community |
Build a REST API with Golang and MongoDB - Gorilla/Mux Version |
https://dev.to/hackmamba/build-a-rest-api-with-golang-and-mongodb-gorillamux-version-57fh
|
Build a REST API with Golang and MongoDB Gorilla Mux VersionRepresentational state transfer REST is an architectural pattern that guides an Application programming interface API design and development REST APIs have become the standard of communication between the server part of the product and its client to increase performance scalability simplicity modifiability visibility portability and reliability This post will discuss building a user management application with Golang using the Mux package and MongoDB At the end of this tutorial we will learn how to structure a Mux application build a REST API and persist our data using MongoDB Gorilla Mux popularly known as Mux is a powerful HTTP router and URL matcher for building Go web servers MongoDB is a document based database management program used as an alternative to relational databases MongoDB supports working with large sets of distributed data with options to store or retrieve information seamlessly You can find the complete source code in this repository PrerequisitesThe following steps in this post require Golang experience Experience with MongoDB isn t a requirement but it s nice to have We will also be needing the following A MongoDB account to host database Signup is completely free Postman or any API testing application of your choice Let s code Getting StartedTo get started we need to navigate to the desired directory and run the command below in our terminal mkdir mux mongo api amp amp cd mux mongo apiThis command creates a mux mongo api folder and navigates into the project directory Next we need to initialize a Go module to manage project dependencies by running the command below go mod init mux mongo apiThis command will create a go mod file for tracking project dependencies We proceed to install the required dependencies with go get u github com gorilla mux go mongodb org mongo driver mongo github com joho godotenv github com go playground validator vgithub com gorilla mux is a package for building web servers go mongodb org mongo driver mongo is a driver for connecting to MongoDB github com joho godotenv is a library for managing environment variable github com go playground validator v is a library for validating structs and fields Application Entry PointWith the project dependencies installed we need to create main go file in the root directory and add the snippet below The snippet above does the following Import the required dependencies Initialize a Mux router using the NewRouter function Use the HandleFunc function that uses net http package as parameters to route to path and a handler function that sets the header type to a JSON and returns a JSON of Hello from Mux amp mongoDB using the encoding json package We also attached the HTTP method to this function Use the http ListenAndServe function to run the application on port Next we can test our application by starting the development server by running the command below in our terminal go run main go Modularization in GolangIt is essential to have a good folder structure for our project Good project structure simplifies how we work with dependencies in our application and makes it easier for us and others to read our codebase To do this we need to create configs controllers models responses and routes folder in our project directory PS The go sum file contains all the dependency checksums and is managed by the go tools We don t have to worry about it configs is for modularizing project configuration filescontrollers is for modularizing application logics models is for modularizing data and database logics responses is for modularizing files describing the response we want our API to give This will become clearer later on routes is for modularizing URL pattern and handler information Setting up MongoDBWith that done we need to log in or sign up into our MongoDB account Click the project dropdown menu and click on the New Project button Enter the golang api as the project name click Next and click Create Project Click on Build a DatabaseSelect Shared as the type of database Click on Create to setup a cluster This might take sometime to setup Next we need to create a user to access the database externally by inputting the Username Password and then clicking on Create User We also need to add our IP address to safely connect to the database by clicking on the Add My Current IP Address button Then click on Finish and Close to save changes On saving the changes we should see a Database Deployments screen as shown below Connecting our application to MongoDBWith the configuration done we need to connect our application with the database created To do this click on the Connect buttonClick on Connect your application change the Driver to Go and the Version as shown below Then click on the copy icon to copy the connection string Setup Environment VariableNext we must modify the copied connection string with the user s password we created earlier and change the database name To do this first we need to create a env file in the root directory and in this file add the snippet below MONGOURI mongodb srv lt YOUR USERNAME HERE gt lt YOUR PASSWORD HERE gt cluster eakf mongodb net myFirstDatabese retryWrites true amp w majoritySample of a properly filled connection string below MONGOURI mongodb srv malomz malomzPassword cluster eakf mongodb net golangDB retryWrites true amp w majorityLoad Environment VariableWith that done we need to create a helper function to load the environment variable using the github com joho godotenv library we installed earlier To do this we need to navigate to the configs folder and in this folder create an env go file and add the snippet below The snippet above does the following Import the required dependencies Create an EnvMongoURI function that checks if the environment variable is correctly loaded and returns the environment variable Connecting to MongoDB To connect to the MongoDB database from our application first we need to navigate to the configs folder and in this folder create a setup go file and add the snippet below The snippet above does the following Import the required dependencies Create a ConnectDB function that first configures the client to use the correct URI and check for errors Secondly we defined a timeout of seconds we wanted to use when trying to connect Thirdly check if there is an error while connecting to the database and cancel the connection if the connecting period exceeds seconds Finally we pinged the database to test our connection and returned the client instance Create a DB variable instance of the ConnectDB This will come in handy when creating collections Create a GetCollection function to retrieve and create collections on the database Next we need to connect to the database when our application startup To do this we need to modify main go as shown below Setup API Route Handler and Response TypeRoute HandlerWith that done we need to create a user route go file inside the routes folder to manage all the user related routes in our application as shown below Next we need to attach the newly created route to the http Server in main go by modifying it as shown below Response TypeNext we need to create a reusable struct to describe our API s response To do this navigate to the responses folder and in this folder create a user response go file and add the snippet below The snippet above creates a UserResponse struct with Status Message and Data property to represent the API response type PS json status json message and json data are known as struct tags Struct tags allow us to attach meta information to corresponding struct properties In other words we use them to reformat the JSON response returned by the API Finally Creating REST API sNext we need a model to represent our application data To do this we need to navigate to the models folder and in this folder create a user model go file and add the snippet below The snippet above does the following Import the required dependencies Create a User struct with required properties We added omitempty and validate required to the struct tag to tell Fiber to ignore empty fields and make the field required respectively Create a User EndpointWith the model setup we can now create a function to create a user To do this we need to navigate to the controllers folder and in this folder create a user controller go file and add the snippet below The snippet above does the following Import the required dependencies Create userCollection and validate variables to create a collection and validate models using the github com go playground validator v library we installed earlier on respectively Create a CreateUser function that returns a net http handler Inside the returned handler we first defined a timeout of seconds when inserting user into the document validating both the request body and required field using the validator library We returned the appropriate message and status code using the UserResponse struct we created earlier Secondly we created a newUser variable inserted it using the userCollection InsertOne function and check for errors if there are any Finally we returned the correct response if the insert was successful w WriteHeader function is used for setting the API status code json NewDecoder s Decode and Encode methods are used to convert JSON into a Go value and vice versa Next we need to update user routes go with the route API URL and corresponding controller as shown below Get a User EndpointTo get the details of a user we need to modify user controller go as shown below The snippet above does the following Import the required dependencies Create a GetAUser function that returns a net http handler Inside the returned handler we first defined a timeout of seconds when finding a user in the document a userId variable to get the user s id from the URL parameter and a user variable We converted the userId from a string to a primitive ObjectID type a BSON type MongoDB uses Secondly we searched for the user using the userCollection FindOne pass the objId as a filter and use the Decode attribute method to get the corresponding object Finally we returned the decoded response Next we need to update user routes go with the route API URL and corresponding controller as shown below PS We also passed a userId as a parameter to the URL path The specified parameter must match the one we specified in the controller Edit a User EndpointTo edit a user we need to modify user controller go as shown below The EditAUser function above does the same thing as the CreateUser function However we included an update variable to get updated fields and updated the collection using the userCollection UpdateOne Lastly we searched for the updated user s details and returned the decoded response Next we need to update user routes go with the route API URL and corresponding controller as shown below Delete a User EndpointTo delete a user we need to modify user controller go as shown below The DeleteAUser function follows the previous steps by deleting the matched record using the userCollection DeleteOne We also checked if an item was successfully deleted and returned the appropriate response Next we need to update user routes go with the route API URL and corresponding controller as shown below Get List of Users EndpointTo get the list of users we need to modify user controller go as shown below The GetAllUsers function follows the previous steps by getting the list of users using the userCollection Find We also read the retuned list optimally using the Next attribute method to loop through the returned list of users Next we need to update user routes go with the route API URL and corresponding controller as shown below Complete user controller go Complete user route go With that done we can test our application by starting the development server by running the command below in our terminal go run main go ConclusionThis post discussed how to structure a Gin gonic application build a REST API and persist our data using MongoDB You may find these resources helpful Gorilla MuxMongoDB Go DriverGo ValidatorGo Environment Loader |
2022-01-03 07:18:24 |
海外TECH |
DEV Community |
Build a REST API with Golang and MongoDB - Gin-gonic Version |
https://dev.to/hackmamba/build-a-rest-api-with-golang-and-mongodb-gin-gonic-version-269m
|
Build a REST API with Golang and MongoDB Gin gonic VersionRepresentational state transfer REST is an architectural pattern that guides an Application programming interface API design and development REST APIs have become the standard of communication between the server part of the product and its client to increase performance scalability simplicity modifiability visibility portability and reliability This post will discuss building a user management application with Golang using the Gin gonic framework and MongoDB At the end of this tutorial we will learn how to structure a Gin gonic application build a REST API and persist our data using MongoDB Gin gonic popularly known as Gin is an HTTP web framework written in Golang with performance and productivity support Gin uses a custom version of HttpRouter a lightweight high performance HTTP request router that navigates through API routes faster than most frameworks out there MongoDB is a document based database management program used as an alternative to relational databases MongoDB supports working with large sets of distributed data with options to store or retrieve information seamlessly You can find the complete source code in this repository PrerequisitesThe following steps in this post require Golang experience Experience with MongoDB isn t a requirement but it s nice to have We will also be needing the following A MongoDB account to host database Signup is completely free Postman or any API testing application of your choice Let s code Getting StartedTo get started we need to navigate to the desired directory and run the command below in our terminal mkdir gin mongo api amp amp cd gin mongo apiThis command creates a gin mongo api folder and navigates into the project directory Next we need to initialize a Go module to manage project dependencies by running the command below go mod init gin mongo apiThis command will create a go mod file for tracking project dependencies We proceed to install the required dependencies with go get u github com gin gonic gin go mongodb org mongo driver mongo github com joho godotenv github com go playground validator vgithub com gin gonic gin is a framework for building web applications go mongodb org mongo driver mongo is a driver for connecting to MongoDB github com joho godotenv is a library for managing environment variables github com go playground validator v is a library for validating structs and fields Application Entry PointWith the project dependencies installed we need to create main go file in the root directory and add the snippet below The snippet above does the following Import the required dependencies Initialize a Gin router using the Default configuration The Default function configures Gin router with default middlewares logger and recovery Use the Get function to route to path and a handler function that returns a JSON of Hello from Gin gonic amp mongoDB Use the Run function to attach the router to an http Server and starts listening and serving HTTP requests on localhost Next we can test our application by starting the development server by running the command below in our terminal go run main go Modularization in GolangIt is essential to have a good folder structure for our project Good project structure simplifies how we work with dependencies in our application and makes it easier for us and others to read our codebase To do this we need to create configs controllers models responses and routes folder in our project directory PS The go sum file contains all the dependency checksums and is managed by the go tools We don t have to worry about it configs is for modularizing project configuration filescontrollers is for modularizing application logics models is for modularizing data and database logics responses is for modularizing files describing the response we want our API to give This will become clearer later on routes is for modularizing URL pattern and handler information Setting up MongoDBWith that done we need to log in or sign up into our MongoDB account Click the project dropdown menu and click on the New Project button Enter the golang api as the project name click Next and click Create Project Click on Build a DatabaseSelect Shared as the type of database Click on Create to setup a cluster This might take sometime to setup Next we need to create a user to access the database externally by inputting the Username Password and then clicking on Create User We also need to add our IP address to safely connect to the database by clicking on the Add My Current IP Address button Then click on Finish and Close to save changes On saving the changes we should see a Database Deployments screen as shown below Connecting our application to MongoDBWith the configuration done we need to connect our application with the database created To do this click on the Connect buttonClick on Connect your application change the Driver to Go and the Version as shown below Then click on the copy icon to copy the connection string Setup Environment VariableNext we must modify the copied connection string with the user s password we created earlier and change the database name To do this first we need to create a env file in the root directory and in this file add the snippet below MONGOURI mongodb srv lt YOUR USERNAME HERE gt lt YOUR PASSWORD HERE gt cluster eakf mongodb net myFirstDatabese retryWrites true amp w majoritySample of a properly filled connection string below MONGOURI mongodb srv malomz malomzPassword cluster eakf mongodb net golangDB retryWrites true amp w majorityLoad Environment VariableWith that done we need to create a helper function to load the environment variable using the github com joho godotenv library we installed earlier To do this we need to navigate to the configs folder and in this folder create an env go file and add the snippet below The snippet above does the following Import the required dependencies Create an EnvMongoURI function that checks if the environment variable is correctly loaded and returns the environment variable Connecting to MongoDB To connect to the MongoDB database from our application first we need to navigate to the configs folder and in this folder create a setup go file and add the snippet below The snippet above does the following Import the required dependencies Create a ConnectDB function that first configures the client to use the correct URI and check for errors Secondly we defined a timeout of seconds we wanted to use when trying to connect Thirdly check if there is an error while connecting to the database and cancel the connection if the connecting period exceeds seconds Finally we pinged the database to test our connection and returned the client instance Create a DB variable instance of the ConnectDB This will come in handy when creating collections Create a GetCollection function to retrieve and create collections on the database Next we need to connect to the database when our application startup To do this we need to modify main go as shown below Setup API Route Handler and Response TypeRoute HandlerWith that done we need to create a user route go file inside the routes folder to manage all the user related routes in our application as shown below Next we need to attach the newly created route to the http Server in main go by modifying it as shown below Response TypeNext we need to create a reusable struct to describe our API s response To do this navigate to the responses folder and in this folder create a user response go file and add the snippet below The snippet above creates a UserResponse struct with Status Message and Data property to represent the API response type PS json status json message and json data are known as struct tags Struct tags allow us to attach meta information to corresponding struct properties In other words we use them to reformat the JSON response returned by the API Finally Creating REST API sNext we need a model to represent our application data To do this we need to navigate to the models folder and in this folder create a user model go file and add the snippet below The snippet above does the following Import the required dependencies Create a User struct with required properties We added omitempty and validate required to the struct tag to tell Gin gonic to ignore empty fields and make the field required respectively Create a User EndpointWith the model setup we can now create a function to create a user To do this we need to navigate to the controllers folder and in this folder create a user controller go file and add the snippet below The snippet above does the following Import the required dependencies Create userCollection and validate variables to create a collection and validate models using the github com go playground validator v library we installed earlier on respectively Create a CreateUser function that returns a Gin gonic handler Inside the returned handler we first defined a timeout of seconds when inserting user into the document validating both the request body and required field using the validator library We returned the appropriate message and status code using the UserResponse struct we created earlier Secondly we created a newUser variable inserted it using the userCollection InsertOne function and check for errors if there are any Finally we returned the correct response if the insert was successful Next we need to update user routes go with the route API URL and corresponding controller as shown below Get a User EndpointTo get the details of a user we need to modify user controller go as shown below The snippet above does the following Import the required dependencies Create a GetAUser function that returns a Gin gonic handler Inside the returned handler we first defined a timeout of seconds when finding a user in the document a userId variable to get the user s id from the URL parameter and a user variable We converted the userId from a string to a primitive ObjectID type a BSON type MongoDB uses Secondly we searched for the user using the userCollection FindOne pass the objId as a filter and use the Decode attribute method to get the corresponding object Finally we returned the decoded response Next we need to update user routes go with the route API URL and corresponding controller as shown below PS We also passed a userId as a parameter to the URL path The specified parameter must match the one we specified in the controller Edit a User EndpointTo edit a user we need to modify user controller go as shown below The EditAUser function above does the same thing as the CreateUser function However we included an update variable to get updated fields and updated the collection using the userCollection UpdateOne Lastly we searched for the updated user s details and returned the decoded response Next we need to update user routes go with the route API URL and corresponding controller as shown below Delete a User EndpointTo delete a user we need to modify user controller go as shown below The DeleteAUser function follows the previous steps by deleting the matched record using the userCollection DeleteOne We also checked if an item was successfully deleted and returned the appropriate response Next we need to update user routes go with the route API URL and corresponding controller as shown below Get List of Users EndpointTo get the list of users we need to modify user controller go as shown below The GetAllUsers function follows the previous steps by getting the list of users using the userCollection Find We also read the retuned list optimally using the Next attribute method to loop through the returned list of users Next we need to update user routes go with the route API URL and corresponding controller as shown below Complete user controller go Complete user route go With that done we can test our application by starting the development server by running the command below in our terminal go run main go ConclusionThis post discussed how to structure a Gin gonic application build a REST API and persist our data using MongoDB You may find these resources helpful Gin gonicMongoDB Go DriverGo ValidatorGo Environment Loader |
2022-01-03 07:17:04 |
ニュース |
BBC News - Home |
Covid: Secondary school testing in England and Scottish rail cancellations |
https://www.bbc.co.uk/news/uk-59856712?at_medium=RSS&at_campaign=KARANGA
|
coronavirus |
2022-01-03 07:30:45 |
ニュース |
BBC News - Home |
How Falklands War and rugby led to 40-year friendship |
https://www.bbc.co.uk/news/uk-wales-59838958?at_medium=RSS&at_campaign=KARANGA
|
mutinous |
2022-01-03 07:05:22 |
サブカルネタ |
ラーブロ |
2021年まとめ的なやつと新年のご挨拶 |
http://ra-blog.net/modules/rssc/single_feed.php?fid=195215
|
配信 |
2022-01-03 07:00:51 |
サブカルネタ |
ラーブロ |
ラーメン専門店 壱発ラーメン 福生店@福生市<ネギチャーシュー> |
http://ra-blog.net/modules/rssc/single_feed.php?fid=195218
|
壱発ラーメン |
2022-01-03 07:00:43 |
北海道 |
北海道新聞 |
立民、選挙ハラスメント調査へ 女性候補増目指し対策強化 |
https://www.hokkaido-np.co.jp/article/629687/
|
女性候補 |
2022-01-03 16:21:00 |
コメント
コメントを投稿