-2

我尝试为使用 Gin 和 Mongodb 的用户设置一个小型 Golang 微服务。

package main

import (
    "context"
    "fmt"
    "github.com/wzslr321/artiver/entity"
    "github.com/wzslr321/artiver/settings"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "log"
    "os"
    "os/signal"
    "syscall"
    "time"
)

type application struct {
    users *entity.UserCollection
}

var app *application

func init() {
    initMongo()
}

func initMongo() {

    oc := options.Client().ApplyURI(settings.MongodbSettings.Uri)

    client, err := mongo.NewClient(oc)
    if err != nil {
        log.Fatalf("Error occured while initializing a new mongo client: %v", err)
    }

    ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
    defer cancel()

    err = client.Connect(ctx)
    if err != nil {
        log.Fatalf("Errorr occurred while connecting to a client: %v", err)
    }

    defer func() {
        if err = client.Disconnect(ctx); err != nil {
            panic(err)
        }
    }()

    log.Println("Successfully connected to the database!")


    app = &application{
        users: &entity.UserCollection{
            C: client.Database("artiver").Collection("users"),
        },
    }
}


func main() {

    router := app.InitRouter()

它在我的 IDE ( GoLand ) 中没有显示任何错误,但是当我尝试构建它时出现错误:

# command-line-arguments
users/cmd/app/main.go:67:15: app.InitRouter undefined (type *application has no field or method InitRouter)

初始化路由器方法自动完成

在上图中很容易看到,我确实可以使用这种方法。它在同一个包中定义。

package main

import (
    "github.com/gin-gonic/gin"
    cors "github.com/rs/cors/wrapper/gin"
    "net/http"
)


func (app *application) InitRouter() *gin.Engine {
    r := gin.New()

    r.Use(gin.Recovery())
    r.Use(cors.Default())

    r.GET("/", func(ctx *gin.Context) {
        ctx.String(http.StatusOK, "Hello World")
    })

    user := r.Group("/api/user")
    {
        user.POST("/add", app.CreateUser)

    }

    return r
}

我不知道我应该如何解决它以及做错了什么。我将不胜感激有关未正确完成的任何提示。

4

1 回答 1

0

根据评论中的@mkopriva 帮助回答。

该问题与未运行所有需要的 .go 文件有关。就我而言,解决方案是在我的 Makefile 中以这种方式构建它: go build -o $(path)users cmd/app/*

在类似的情况下,go run .很可能会完成这项工作。

于 2021-08-02T18:36:23.000 回答