I am new to golang and I wanted to implement a http server using the in built net/http package. I was able to implement a health route for my webserver. Then I tried creating handler for my user controller but it didnt work and I aslways got the response as
404 page not found
so I tried to create a user route on the same level as health route but I still got the same response
Here is the main function
func main() {
.....
cleanup, err := run(env)
....
}
func run(env config.EnvVars) (func(), error) {
app, cleanup, err := buildServer(env)
if err != nil {
return nil, err
}
// start the server
go func() {
if err := app.ListenAndServe(); err != nil {
slog.Error("Error while starting server - %v", err)
}
}()
return func() {
cleanup()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := app.Shutdown(ctx); err != nil {
slog.Error("Error while shutting down server - %v", err)
}
}, nil
}
func buildServer(env config.EnvVars) (*http.Server, func(), error) {
slog.Info("Initializing DB connection")
// init the storage
db, err := storage.BootstrapSqlite3(env.DB_FILE, 10*time.Second)
if err != nil {
return nil, nil, err
}
slog.Info("Initialized DB connection")
slog.Info("Initializing routers")
serverConfig := api.NewAPIServer("0.0.0.0:"+env.PORT, db)
app := serverConfig.InitaliseHTTPServer()
slog.Info("Initialized routers")
return app, func() {
storage.CloseSqlite3(db)
}, nil
}
and here is the api.go file
package api
import (
"database/sql"
"net/http"
// "github.com/rampa2510/contracts-poc/internal/api/middleware"
// "github.com/rampa2510/contracts-poc/internal/api/services/user"
"github.com/rampa2510/contracts-poc/internal/utils"
"golang.org/x/exp/slog"
)
type APIServer struct {
addr string
db *sql.DB
}
func NewAPIServer(addr string, db *sql.DB) *APIServer {
return &APIServer{
addr: addr,
db: db,
}
}
func (serverConfig *APIServer) InitaliseHTTPServer() *http.Server {
router := http.NewServeMux()
router.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
response := map[string]string{
"status": "OK",
}
utils.SendResponse(w, http.StatusOK, response)
})
router.HandleFunc("GET /users", func(w http.ResponseWriter, r *http.Request) {
resp := map[string]string{
"status": "Ok",
}
utils.SendResponse(w, http.StatusOK, resp)
})
// userStorage := user.NewUserDb(serverConfig.db)
// userController := user.NewUserController(userStorage)
// user.RegisterUserRouter(router, userController)
slog.Info("Server running", "addr", serverConfig.addr)
// stack := middleware.CreateStack(middleware.Logging, middleware.ErrorHandling)
server := &http.Server{Addr: serverConfig.addr, Handler: router}
return server
}
I am getting 404 on the users endpoint but not on the health endpoint even though they are very similar.
here is the github repo as well if you would like to take a look
1