Skip to content
This repository was archived by the owner on Sep 1, 2020. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,7 @@ that is named `ping` and returns no content with 200 status.
}
```

4. Use [golangci-lint](https://github.com/golangci/golangci-lint) to lint your code :rocket:
5. Write tests for your endpoints. In the tests you must use MongoDB and check your recently created record.

For conntecting to Mongodb use the offical driver that can be found [here](https://github.com/mongodb/mongo-go-driver).
61 changes: 56 additions & 5 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,58 @@
package main
package testing101
import (
"context"
"time"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"go.mongodb.org/mongo-driver/mongo"
"github.com/labstack/echo"
"go.mongodb.org/mongo-driver/mongo/options"
)

import "fmt"

func main() {
fmt.Println("18.20 at Sep 07 2016 7:20 IR721")
type test struct {
Lat string `json:"lat"`
Lng string `json:"lng"`
}
func JsonHandler(c echo.Context) (err error) {
t :=test{}
defer c.Request().Body.Close()
b,err := ioutil.ReadAll(c.Request().Body)
if err!=nil {
log.Printf("failed to rendering request body:%s",err)
return c.String(http.StatusInternalServerError,"")
}
err=json.Unmarshal(b,&t)
if err!=nil {
log.Printf("failed to Unmarshaling:%s",err)
return c.String(http.StatusInternalServerError,"")
}
client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please separate the database connection creation phase from the handler create a stand-alone function for it.

if err!= nil{
log.Fatal(err)
}
ctx,cancel:= context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
if err!= nil{
log.Fatal(err)
}
collection := client.Database("testing").Collection("geo")
res, err := collection.InsertOne(ctx,t)
if err!= nil{
log.Fatal(err)
}
id := res.InsertedID
defer cancel()
return c.String(http.StatusOK, fmt.Sprintf("%s\n%s\n%s\n",id, string(t.Lat),string(t.Lng)))
}
func Pinging(c echo.Context) error {
return c.String(http.StatusOK, "man amdam")
}
func NewServer() {
e := echo.New()
e.GET("/ping",Pinging)
e.POST("/posting",JsonHandler)
e.Logger.Fatal(e.Start(":1323"))
}