Junior — Middle
What methods do you use or know for implementing user login processes?
sobes.tech AI
Answer from AI
To implement user login in Go, the following methods are usually used:
- Authentication with username and password with hashed password storage (e.g., bcrypt).
- Using JWT (JSON Web Tokens) to create a session token after successful login.
- OAuth2 for authorization through third-party services (Google, Facebook, etc.).
- Sessions with cookies for web applications.
Example of simple login with password verification:
import (
"golang.org/x/crypto/bcrypt"
"net/http"
)
func loginHandler(w http.ResponseWriter, r *http.Request) {
username := r.FormValue("username")
password := r.FormValue("password")
// Retrieve hashed password from DB by username
hashedPassword := getHashedPasswordFromDB(username)
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
if err != nil {
http.Error(w, "Invalid credentials", http.StatusUnauthorized)
return
}
// Create session or JWT and send to client
}
Thus, the process includes password verification, token or session creation, and user state management.