当我尝试调用API时,本地服务器返回“ http:紧急服务[:: 1]:52781:运行时错误:无效的内存地址或nil指针取消引用”

I followed the guide to write the mongodb API here: https://www.thepolyglotdeveloper.com/2019/02/developing-restful-api-golang-mongodb-nosql-database/

The guide's code run perfectly. But when I tried to split the code into small packages to add more cases and easier to read, the server always return as the title. Below is the code, I just split the guide's code into small packages not add anything new or remove anything. What did I do wrong or what am I missing? https://github.com/imperiustx/mongo_golang

You are facing this problem because the client variable in the middleware.go file is nil.

client is a dependency here. It has to be injected from main package to middleware package.

Fix:-

middleware.go

type endpoints struct {
    client *mongo.Client
}

func NewEndpoints(client *mongo.Client) *endpoints {
    return &endpoints{
        client: client,
    }
}

func (e *endpoints) CreatePersonEndpoint(response http.ResponseWriter, request *http.Request) {
    response.Header().Set("content-type", "application/json")
    var person models.Person
    _ = json.NewDecoder(request.Body).Decode(&person)
    collection := e.client.Database("thepolyglotdeveloper").Collection("people")
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    result, _ := collection.InsertOne(ctx, person)
    json.NewEncoder(response).Encode(result)
}
func (e *endpoints) GetPeopleEndpoint(response http.ResponseWriter, request *http.Request) {
    response.Header().Set("content-type", "application/json")
    var people []models.Person
    collection := e.client.Database("thepolyglotdeveloper").Collection("people")
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()
    cursor, err := collection.Find(ctx, bson.M{})
    if err != nil {
        response.WriteHeader(http.StatusInternalServerError)
        response.Write([]byte(`{ "message": "` + err.Error() + `" }`))
        return
    }
    defer cursor.Close(ctx)
    for cursor.Next(ctx) {
        var person models.Person
        cursor.Decode(&person)
        people = append(people, person)
    }
    if err := cursor.Err(); err != nil {
        response.WriteHeader(http.StatusInternalServerError)
        response.Write([]byte(`{ "message": "` + err.Error() + `" }`))
        return
    }
    json.NewEncoder(response).Encode(people)
}
func (e *endpoints) GetPersonEndpoint(response http.ResponseWriter, request *http.Request) {
    response.Header().Set("content-type", "application/json")
    params := mux.Vars(request)
    id, _ := primitive.ObjectIDFromHex(params["id"])
    var person models.Person
    collection := e.client.Database("thepolyglotdeveloper").Collection("people")
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()
    err := collection.FindOne(ctx, models.Person{ID: id}).Decode(&person)
    if err != nil {
        response.WriteHeader(http.StatusInternalServerError)
        response.Write([]byte(`{ "message": "` + err.Error() + `" }`))
        return
    }
    json.NewEncoder(response).Encode(person)
}

main.go

func main() {
    fmt.Println("Starting the application...")
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
    client, _ = mongo.Connect(ctx, clientOptions)

    endpoints := middleware.NewEndpoints(client) // injecting the dependency
    router := mux.NewRouter()
    router.HandleFunc("/person", endpoints.CreatePersonEndpoint).Methods("POST")
    router.HandleFunc("/people", endpoints.GetPeopleEndpoint).Methods("GET")
    router.HandleFunc("/person/{id}", endpoints.GetPersonEndpoint).Methods("GET")
    http.ListenAndServe(":12345", router)
}