[error] failed to initialize database, got error Binary was compiled with 'CGO_ENABLED=0', go-sqlite3 requires cgo to work. This is a stub 2024/09/07 02:28:01 Failed to connect to the database: Binary was compiled with 'CGO_ENABLED=0', go-sqlite3 requires

[error] failed to initialize database, got error Binary was compiled with ‘CGO_ENABLED=0’, go-sqlite3 requires cgo to work. This is a stub
2024/09/07 02:28:01 Failed to connect to the database: Binary was compiled with ‘CGO_ENABLED=0’, go-sqlite3 requires cgo to work. This is a stub
exit status 1

backend

package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/gorilla/mux"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

var db *gorm.DB

func main() {
	var err error
	// Open the SQLite database
	db, err = gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
	if err != nil {
		log.Fatalf("Failed to connect to the database: %v", err)
	}

	// Auto-migrate the User model
	err = db.AutoMigrate(&User{})
	if err != nil {
		log.Fatalf("Failed to migrate database schema: %v", err)
	}

	// Initialize the router
	r := mux.NewRouter()
	r.HandleFunc("/", HomeHandler)
	r.HandleFunc("/hello/{name:[a-zA-Z]+}", HelloHandler)
	r.HandleFunc("/users", CreateUserHandler).Methods("POST")

	// Start the server
	fmt.Println("Server starting on port 9999")
	log.Fatal(http.ListenAndServe(":9999", r))
}

type User struct {
	gorm.Model
	Name  string
	Email string
}

func HomeHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Welcome to the Home Page!")
}

func HelloHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	name := vars["name"]
	fmt.Fprintf(w, "Hello, %s!", name)
}

func CreateUserHandler(w http.ResponseWriter, r *http.Request) {
	// For demonstration purposes, handle user creation here
	// You might want to parse request body and insert user into the database

	// Example of creating a new user (make sure to parse JSON and validate input)
	var user User
	if err := r.ParseForm(); err != nil {
		http.Error(w, "Unable to parse form", http.StatusBadRequest)
		return
	}

	// Dummy data to demonstrate user creation
	user.Name = "John Doe"
	user.Email = "john@example.com"

	// Save user to the database
	if err := db.Create(&user).Error; err != nil {
		http.Error(w, "Failed to create user", http.StatusInternalServerError)
		return
	}

	fmt.Fprintf(w, "User created!")
}

What is the question? There is none in the topic.

Error is clear. You need to enable CGO during build or use a driver which was written in go without using C bindings

use CGO_ENABLED=1 to build.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.