Create a simple Golang rest api with Mux and MongoDb

Ha Doan
2 min readJun 1, 2020
golang app in visa sponsor job architect

I will use Mux to create rest api that connect from MongoDb database

In mongodb, I have Default database with AppJobs collection, the api simply get list of job in this collection.

  • Firstly we need to install Mux and MongoDb Library
go get -u github.com/gorilla/mux
go get go.mongodb.org/mongo-driver/mongo
  • Then create main.go file and init golang app
package mainimport “fmt”func main() {     fmt.Println(“Starting the application …”)}

To test golang app, run command go run main.go in your terminal

  • Define Job model
  • Connect to mongodb
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)client, _ = mongo.Connect(ctx, options.Client().ApplyURI(“mongo://localhost:27017”))
  • Register router and Endpoint
router := mux.NewRouter()router.HandleFunc(“/jobs”, getJobPostsEndpoint).Methods(“GET”)http.ListenAndServe(“:12345”, router)

For this definition, I create “/jobs” endpoint to to get all jobs from mongo db. now we need to create the endpoint and fetch data from mongodb

  • Create function to get data from mongodb
  • Done, now we can test the api by run command
go run main.go
  • Result from this api:
  • Full source-code

This api is very simple, I will add more api and refactor in the future when I need to integrate more functions

The full source-code for this project is at https://github.com/hadoan/no-border-jobs/tree/dev

--

--