Last active
December 30, 2022 07:17
-
-
Save liuggio/6c89e5eb9e6d47c1da7933a7762e1b3c to your computer and use it in GitHub Desktop.
Golang api code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"database/sql" | |
"fmt" | |
"log" | |
"net/http" | |
"time" | |
"os" | |
"strings" | |
"github.com/dgrijalva/jwt-go" | |
"github.com/gin-gonic/gin" | |
_ "github.com/go-sql-driver/mysql" | |
"github.com/joho/godotenv" | |
"github.com/google/uuid" | |
) | |
// Customer represents a customer | |
type CustomerCreate struct { | |
FirstName string `json:"firstName"` | |
LastName string `json:"lastName"` | |
Email string `json:"email"` | |
Phone string `json:"phone"` | |
Country string `json:"country"` | |
BillingDetails []interface{} `json:"billingDetails"` | |
AcceptEmailMarketing bool `json:"acceptEmailMarketing"` | |
StripeCustomerID string `json:"stripeCustomerId"` | |
AngelStorageIds []interface{} `json:"angelStorageIds"` | |
IsAngel bool `json:"isAngel"` | |
Roles []string `json:"roles"` | |
Password string `json:"password"` | |
} | |
type requestCustomerCreate struct { | |
Customer CustomerCreate `json:"customer"` | |
} | |
// JWTClaims represents the claims in a JWT token | |
type JWTClaims struct { | |
TokenVersion string `json:"tokenVersion"` | |
UUID string `json:"uuid"` | |
Email string `json:"email"` | |
ExpireAt time.Time `json:"expireAt"` | |
Name string `json:"name"` | |
CustomerID string `json:"customerId"` | |
AngelCanReadStorageIds []interface{} `json:"angelCanReadStorageIds"` | |
IsAffiliate bool `json:"isAffiliate"` | |
EmailHash string `json:"emailHash"` | |
AffiliateCode interface{} `json:"affiliateCode"` | |
Roles []string `json:"roles"` | |
jwt.StandardClaims | |
} | |
func main() { | |
gin.ForceConsoleColor() | |
err := godotenv.Load() | |
if err != nil { | |
fmt.Println("Error loading .env file") | |
return | |
} | |
// Get the environment variables | |
host := os.Getenv("MYSQL_HOST") | |
user := os.Getenv("MYSQL_USER") | |
password := os.Getenv("MYSQL_PASSWORD") | |
database := os.Getenv("MYSQL_DATABASE") | |
stringCnn := fmt.Sprintf("%s:%s@tcp(%s)/%s", user, password, host, database) | |
fmt.Println(stringCnn) | |
// Connect to the database | |
db, err := sql.Open("mysql", stringCnn) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
defer db.Close() | |
// Set the maximum number of connections in the pool | |
db.SetMaxOpenConns(10) | |
// Set the maximum number of idle connections in the pool | |
db.SetMaxIdleConns(5) | |
// Set the maximum lifetime of a connection | |
db.SetConnMaxLifetime(time.Minute * 5) | |
// Create the HTTP router | |
// Initialize the router | |
router := gin.Default() | |
router.Use(gin.Logger()) | |
// Add a route for the POST request | |
router.POST("/en/user/me", func(c *gin.Context) { | |
// Bind the request body to a Customer struct | |
var requestCustomerCreate requestCustomerCreate | |
if err := c.ShouldBindJSON(&requestCustomerCreate); err != nil { | |
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | |
return | |
} | |
customer := requestCustomerCreate.Customer | |
log.Println("====== Only Bind By Query String ======%v", customer) | |
// Check if the email already exists in the database | |
var count int | |
err = db.QueryRow("SELECT COUNT(*) FROM customers WHERE email = ?", customer.Email).Scan(&count) | |
if err != nil { | |
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | |
return | |
} | |
if count > 0 { | |
c.JSON(http.StatusBadRequest, gin.H{"error": "Email already exists"}) | |
return | |
} | |
roles := strings.Join(customer.Roles, ",") | |
// Insert the customer into the database | |
fmt.Println(customer) | |
res, err := db.Exec("INSERT INTO customers (first_name, last_name, email, phone, country, password, roles) VALUES (?, ?, ?, ?, ?, ?, ?)", | |
customer.FirstName, customer.LastName, customer.Email, customer.Phone, customer.Country, customer.Password, roles) | |
if err != nil { | |
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | |
return | |
} | |
customerID, err := res.LastInsertId() | |
if err != nil { | |
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | |
return | |
} | |
ui := uuid.New() | |
// Create the JWT token | |
expireAt := time.Now().Add(time.Hour * 24 * 30) | |
claims := JWTClaims{ | |
TokenVersion: "1ac39df4537c1029b6d23e4647338985622a6615", | |
UUID: ui.String(), | |
Email: customer.Email, | |
ExpireAt: expireAt, | |
Name: fmt.Sprintf("%s %s", customer.FirstName, customer.LastName), | |
CustomerID: fmt.Sprintf("%d",customerID), | |
Roles: customer.Roles, | |
} | |
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) | |
signedToken, err := token.SignedString([]byte("secret")) | |
if err != nil { | |
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | |
return | |
} | |
c.JSON(http.StatusCreated, gin.H{"token": signedToken}) | |
}) | |
// Start the server | |
router.Run(":9999") | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment