Registration and Login are the vital parts of a web application. Here I have built a registration and login template code in Golang. For storing data, I have used the MongoDB NoSQL database. For routing in Golang, I have used the gorilla mux router and any further API call after login will be secured with JWT.
type User struct{
FirstName string `json:"firstname" bson:"firstname"`
LastName string `json:"lastname" bson:"lastname"`
Email string `json:"email" bson:"email"`
Password string `json:"password" bson:"password"`
}
Here is a pretty simple User struct which contains First Name, Last Name, Email and Password. All are in string data type, ‘json’ is used for data parsing for server to client and vice versa and ‘bson’ is used for storing data in MongoDB.
func userSignup(response http.ResponseWriter, request *http.Request{
response.Header().Set("Content-Type","application/json")
var user User json.NewDecoder(request.Body).Decode(&user)
user.Password = getHash([]byte(user.Password))
collection := client.Database("GODB").Collection("user")
ctx,_ := context.WithTimeout(context.Background(),
10*time.Second)
result,err := collection.InsertOne(ctx,user)
if err!=nil{
response.WriteHeader(http.StatusInternalServerError)
response.Write([]byte(`{"message":"`+err.Error()+`"}`))
return
}
json.NewEncoder(response).Encode(result)
}
Above userSignup function is doing the user registration part. Here response body’s json data coming from client browser is decoded in a User struct. Password is hashed before storing in Database with below code snippet. For password hasing I have used bcrypt.
func getHash(pwd []byte) string {
hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost)
if err != nil {
log.Println(err)
}
return string(hash)
}
#go #golang #mongodb #jwt