Golang初学者无法解决这个问题。

huangapple go评论83阅读模式
英文:

Golang beginner not able solve the problem

问题

我将为您翻译以下内容:

我想通过这种方法创建一个用户登录功能。这需要分为三个部分,与用户注册相同,但我不知道如何做到这一点。您能否告诉我如何编写用户登录逻辑?它是使用gorilla mux创建的。

首先,在db_service.go中创建一个方法,然后在login_service.go中创建一个方法,最后在login.go中创建一个方法。

以下是db_service.go的代码:

/* 用于创建MongoDB客户端的单例对象。
通过GetMongoClient()进行初始化和公开。*/

var clientInstance *mongo.Client

// 在GetMongoClient()中创建单例客户端对象时使用。
var clientInstanceError error

// 用于仅执行一次客户端创建过程。
var mongoOnce sync.Once

// 我使用下面的常量来保存所需的数据库配置。
const (
	CONNECTIONSTRING = "http://127.0.0.1:27017"
	AUTH_DB          = "Cluster0"
	USER_COLLECTION  = "user"
)

// GetMongoClient - 返回与MongoDB连接的客户端
func GetMongoClient() (*mongo.Client, error) {

	// 仅执行一次连接创建操作。
	mongoOnce.Do(func() {
		// 设置客户端选项
		clientOptions := options.Client().ApplyURI(CONNECTIONSTRING)
		// 连接到MongoDB
		client, err := mongo.Connect(context.TODO(), clientOptions)
		if err != nil {
			clientInstanceError = err
		}
		// 检查连接
		err = client.Ping(context.TODO(), nil)
		if err != nil {
			clientInstanceError = err
		}
		log.Println("Connected Mongodb!")
		clientInstance = client
	})

	return clientInstance, clientInstanceError
}

// User_Collection - 在集合中插入新文档。
func User_Collection(user *model.User) (*mongo.InsertOneResult, error) {

	// 创建与数据库中相应集合的句柄。
	collection := clientInstance.Database(AUTH_DB).Collection(USER_COLLECTION)

	// 执行InsertOne操作并根据错误进行验证。
	return collection.InsertOne(context.TODO(), user)
}

login_service.go 包含了用户注册的代码:

func Register_User(user *model.User) (interface{}, error) {

	user.CreatedAt = time.Now().UTC()
	user.UpdatedAt = time.Now().UTC()
	if result, err := util.User_Collection(user); err == nil {
		return result.InsertedID, err
	} else {
		return nil, err
	}
}

用户注册的代码:

func Register(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	var user model.User
	if err := json.NewDecoder(r.Body).Decode(&user); err == nil {

		if _, err := service.Register_User(&user); err == nil {
			w.WriteHeader(http.StatusCreated)
			json.NewEncoder(w).Encode(user)
		} else {
			w.WriteHeader(http.StatusInternalServerError)
			json.NewEncoder(w).Encode(err)
		}

	} else {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

}
英文:

I would like to make a user login from this method. This has to be in three parts. The same as user registration, but I am not understanding how to do this? Could you please write how I can write a user login logic this same way? It is created using gorilla mux.

One method has to be in db_service.go then one method has to be in login_service.go
one method has to be in login.go.

This is db_service.go code:

  /* Used to create a singleton object of MongoDB client.
Initialized and exposed through  GetMongoClient().*/

var clientInstance *mongo.Client

//Used during creation of singleton client object in GetMongoClient().
var clientInstanceError error

//Used to execute client creation procedure only once.
var mongoOnce sync.Once

//I have used below constants just to hold required database config's.
const (
	CONNECTIONSTRING = "http://127.0.0.1:27017"
	AUTH_DB          = "Cluster0"
	USER_COLLECTION  = "user"
)

//GetMongoClient - Return mongodb connection to work with
func GetMongoClient() (*mongo.Client, error) {

	//Perform connection creation operation only once.
	mongoOnce.Do(func() {
		// Set client options
		clientOptions := options.Client().ApplyURI(CONNECTIONSTRING)
		// Connect to MongoDB
		client, err := mongo.Connect(context.TODO(), clientOptions)
		if err != nil {
			clientInstanceError = err
		}
		// Check the connection
		err = client.Ping(context.TODO(), nil)
		if err != nil {
			clientInstanceError = err
		}
		log.Println("Connected Mongodb!")
		clientInstance = client
	})

	return clientInstance, clientInstanceError
}

//CreateIssue - Insert a new document in the collection.
func User_Collection(user *model.User) (*mongo.InsertOneResult, error) {

	//Create a handle to the respective collection in the database.
	collection := clientInstance.Database(AUTH_DB).Collection(USER_COLLECTION)

	//Perform InsertOne operation & validate against the error.
	return collection.InsertOne(context.TODO(), user)
}

login_service.go contained code for user registration:

 func Register_User(user *model.User) (interface{}, error) {

	user.CreatedAt = time.Now().UTC()
	user.UpdatedAt = time.Now().UTC()
	if result, err := util.User_Collection(user); err == nil {
		return result.InsertedID, err
	} else {
		return nil, err
	}
}

User registration code:

func Register(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")

var user model.User
if err := json.NewDecoder(r.Body).Decode(&user); err == nil {

	if _, err := service.Register_User(&user); err == nil {
		w.WriteHeader(http.StatusCreated)
		json.NewEncoder(w).Encode(user)
	} else {
		w.WriteHeader(http.StatusInternalServerError)
		json.NewEncoder(w).Encode(err)
	}

} else {
	http.Error(w, err.Error(), http.StatusBadRequest)
	return
}

}

答案1

得分: 1

处理程序的示例代码如下:

func Login(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")

    var user model.User
    if err := json.NewDecoder(r.Body).Decode(&user); err == nil {

        if _, err := service.Login_User(&user); err == nil {
            json.NewEncoder(w).Encode(user)
        } else {
            w.WriteHeader(http.StatusInternalServerError)
            json.NewEncoder(w).Encode(err)
        }

    } else {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }
}

数据库的示例代码如下(需要实现查询而不是插入):

func Login_User(user *model.User) (interface{}, error) {

    // 实现这个查询
    if result, err := util.Find_User(user); err == nil {
        return result, err
    } else {
        return nil, err
    }
}

请注意,这只是示例代码,具体实现可能会根据你的需求和数据库类型而有所不同。

英文:

Something like this for the handler

func Login(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")

    var user model.User
    if err := json.NewDecoder(r.Body).Decode(&user); err == nil {

      if _, err := service.Login_User(&user); err == nil {
          json.NewEncoder(w).Encode(user)
      } else {
          w.WriteHeader(http.StatusInternalServerError)
          json.NewEncoder(w).Encode(err)
      }

    } else {
          http.Error(w, err.Error(), http.StatusBadRequest)
          return
    }
}

And something like this for the DB (Need to implement the query instead of insert)

 func Login_User(user *model.User) (interface{}, error) {

    // Implement this query
    if result, err := util.Find_User(user); err == nil {
        return result, err
    } else {
        return nil, err
    }
}

huangapple
  • 本文由 发表于 2021年11月11日 10:42:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/69922591.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定