Skip to content

Instantly share code, notes, and snippets.

@doorbash
Last active September 10, 2019 07:27
Show Gist options
  • Save doorbash/b85b509835c7b673816e15af733db667 to your computer and use it in GitHub Desktop.
Save doorbash/b85b509835c7b673816e15af733db667 to your computer and use it in GitHub Desktop.
github.com/doorbash/my-api/routes/user.go
package routes
import (
"context"
"encoding/json"
"fmt"
"github.com/doorbash/my-api/model"
"github.com/gorilla/mux"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"log"
"net/http"
"time"
)
var database *mongo.Database
func listAll(rw http.ResponseWriter, r *http.Request) {
users := *database.Collection("users")
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
cur, err := users.Find(ctx, bson.D{})
if cur != nil {
defer cur.Close(ctx)
}
if err != nil {
log.Println(err)
rw.WriteHeader(500)
fmt.Fprint(rw, "")
return
}
list := []model.User{}
for cur.Next(ctx) {
var result bson.M
err := cur.Decode(&result)
if err != nil {
log.Println(err)
rw.WriteHeader(500)
fmt.Fprint(rw, "")
break
}
// for a, b := range result {
// fmt.Printf("[%v] = %T\n", a, b)
// }
emojis := []int32{}
for _, emoji := range result["emojis"].(primitive.A) {
emojis = append(emojis, emoji.(int32))
}
user := model.User{
Id: fmt.Sprintf("%v", result["_id"].(primitive.ObjectID).Hex()),
Name: result["name"].(string),
Coins: result["coins"].(int32),
Emojis: emojis,
CreatedAt: int64(result["createdAt"].(primitive.DateTime)),
}
list = append(list, user)
}
if err := cur.Err(); err != nil {
log.Println(err)
rw.WriteHeader(500)
fmt.Fprint(rw, "")
return
}
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(200)
json.NewEncoder(rw).Encode(list)
}
func get(rw http.ResponseWriter, r *http.Request) {
var id = mux.Vars(r)["id"]
users := *database.Collection("users")
var result primitive.D
objectID, _ := primitive.ObjectIDFromHex(id)
filter := bson.M{"_id": objectID}
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
err := users.FindOne(ctx, filter).Decode(&result)
if err != nil || len(result) == 0 {
rw.WriteHeader(404)
fmt.Fprint(rw, "")
return
}
fmt.Println(result)
fmt.Printf("%T\n", result)
// for a, b := range result {
// fmt.Printf("[%v] = %T\n", a, b)
// }
user := model.User{}
for _, item := range result {
switch item.Key {
case "_id":
user.Id = fmt.Sprintf("%v", item.Value.(primitive.ObjectID).Hex())
case "name":
user.Name = item.Value.(string)
case "coins":
user.Coins = item.Value.(int32)
case "createdAt":
user.CreatedAt = int64(item.Value.(primitive.DateTime))
case "emojis":
emojis := []int32{}
for _, emoji := range item.Value.(primitive.A) {
emojis = append(emojis, emoji.(int32))
}
user.Emojis = emojis
default:
panic("what?")
}
}
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(200)
json.NewEncoder(rw).Encode(user)
}
func InitUserRouter(db *mongo.Database) {
database = db
r := mux.NewRouter()
r.HandleFunc("/user/", listAll)
r.HandleFunc("/user/{id}", get)
http.Handle("/user/", r)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment