1

所以我目前有一个函数可以接收一个字符串APIKey来检查我的 Mongo 集合。如果没有找到(未通过身份验证),则返回 false - 如果找到用户,则返回 true。但是,我的问题是我不确定如何将其与 Martini POST 路线集成。这是我的代码:

package main

import (
    "context"
    "fmt"
    "log"
    "os"

    "github.com/go-martini/martini"
    _ "github.com/joho/godotenv/autoload"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

type User struct {
    Name   string
    APIKey string
}

func validateAPIKey(users *mongo.Collection, APIKey string) bool {
    var user User

    filter := bson.D{{"APIKey", APIKey}}
    if err := users.FindOne(context.TODO(), filter).Decode(&user); err != nil {
        fmt.Printf("Found 0 results for API Key: %s\n", APIKey)
        return false
    }

    fmt.Printf("Found: %s\n", user.Name)
    return true
}

func uploadHandler() {

}

func main() {
    mongoURI := os.Getenv("MONGO_URI")
    mongoOptions := options.Client().ApplyURI(mongoURI)
    client, _ := mongo.Connect(context.TODO(), mongoOptions)
    defer client.Disconnect(context.TODO())
    if err := client.Ping(context.TODO(), nil); err != nil {
        log.Fatal(err, "Unable to access MongoDB server, exiting...")
    }

    // users := client.Database("sharex_api").Collection("authorized_users") // commented out when testing to ignore unused warnings

    m := martini.Classic()
    m.Post("/api/v1/upload", uploadHandler)

    m.RunOnAddr(":8085")
}

如果单独测试该validateAPIKey函数完全按照预期工作,我只是不确定如何为特定端点运行此函数(在本例中为 /api/v1/upload)。

4

0 回答 0