Home > Software engineering >  Golang beginner not able solve the problem
Golang beginner not able solve the problem

Time:11-11

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
}

}

CodePudding user response:

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
    }
}
  • Related