英文:
Not connecting to MongoDB database
问题
我正在尝试使用Postman向Mux Router发送POST请求。但每次我尝试发送POST请求时,Postman都会告诉我"ERROR: socket hang up"。
然后在Go中,我也收到以下错误:
http: panic serving [::1]:64995: runtime error: invalid memory address or nil pointer dereference
代码:
type Person struct {
    ID          primitive.ObjectID     `json:"_id,omitempty" bson:"_id,omitempty"`
    Firstname   string                `json:"firstname,omitempty" bson:"firstname,omitempty"`
    Lastname    string                `json:"lastname,omitempty" bson:"lastname,omitempty"`
}
var client *mongo.Client // 创建mongo客户端
func CreatePersonEndpoint(w http.ResponseWriter, r *http.Request){
    w.Header().Add("Content-Type", "application/json")
    var person Person
    json.NewDecoder(r.Body).Decode(&person)
    collection := client.Database("People").Collection("people")
    ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
    result, _:= collection.InsertOne(ctx, person)
    json.NewEncoder(w).Encode(result)
}
func main(){
    ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
    client, _ := mongo.Connect(ctx, options.Client().ApplyURI("mongodb+srv://username:password[@cluster0.51awc.mongodb.net/test"))
    client.Connect(ctx)
    client.Ping(ctx, readpref.Primary())
    databases, _ := client.ListDatabaseNames(ctx, bson.M{})
    fmt.Println(databases)
    r := mux.NewRouter()
    r.HandleFunc("/person", CreatePersonEndpoint).Methods("POST")
    http.ListenAndServe(":8000", r)
}
这是我在MongoDB中创建的可用数据库:
[Hotels People admin local]
在"People"数据库下,我创建了一个"people"集合。
英文:
I am trying to do a POST request using postman to Mux Router. But each time I try to do the POST request, PostMan always tells me "ERROR: socket hang up".
Then in Go I also receive the following error:
http: panic serving [::1]:64995: runtime error: invalid memory address or nil pointer dereference
Code:
type Person struct {
	ID 			primitive.ObjectID 	`json:"_id,omitempty" bson:"_id,omitempty"`
	Firstname 	string				`json:"firstname,omitempty" bson:"firstname,omitempty"`
	Lastname	string				`json:"lastname,omitempty" bson:"lastname,omitempty"`
}
var client *mongo.Client // create mongo client
func CreatePersonEndpoint(w http.ResponseWriter, r *http.Request){
	w.Header().Add("Content-Type", "application/json")
	var person Person
	json.NewDecoder(r.Body).Decode(&person)
	collection := client.Database("People").Collection("people")
	ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
	result, _:= collection.InsertOne(ctx, person)
	json.NewEncoder(w).Encode(result)
}
func main(){
	ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
	client, _ := mongo.Connect(ctx, options.Client().ApplyURI("mongodb+srv://username:password[@cluster0.51awc.mongodb.net/test"))
	client.Connect(ctx)
	client.Ping(ctx, readpref.Primary())
	databases, _ := client.ListDatabaseNames(ctx, bson.M{})
	fmt.Println(databases)
	r := mux.NewRouter()
	r.HandleFunc("/person", CreatePersonEndpoint).Methods("POST")
	http.ListenAndServe(":8000", r)
}
Here are the available Databases I have created in MongoDB:
[Hotels People admin local]
Under the "People" Database I created a "people" collection.
答案1
得分: 3
你在main函数中使用:=运算符创建了一个新的client变量。请使用=将其赋值给全局的client变量。
英文:
You're creating a new client variable in your main function with the := operator. Use = to assign to your global client variable.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论