Skip to content

Unable to pass DB in echo.Context to handler function #2075

@cyberkryption

Description

@cyberkryption

Issue Description

Checklist

  • Dependencies installed
  • No typos
  • Searched existing issues and docs

Expected behaviour

I am new to echo and am building a rest api using swagger. I want to add db to echo.Context so that it is defined for api handlers giving them access to database.

I searched the issues and found #514 which seems to suggest that adding something like e.Context().Set("db", db) in place of the ContxtDB function in main.go might work but this failed as well.

However, I am struggling to understand why the db is undefined. Have I made a silly mistake somewhere that I just cant see?

Actual behaviour

db undefined in licence.go in api package

Steps to reproduce

See below

Working code to debug

package main

import (
	"fmt"
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	"github.com/swaggo/echo-swagger"
	_ "github.com/mattn/go-sqlite3"
	"licence-server/api"
	"licence-server/database"
	"licence-server/docs"
	"licence-server/middlewares"

func main() {
	db := database.Connect()
	defer db.Close()

	e := echo.New()

	// Pass database to all handlers by adding to echo context
	e.Use(middlewares.ContextDB(db))

	e.Use(middleware.Logger())

      e.POST("/api/v1/licence", api.Create_a_Licence)

Licence.go in licence-server/api.go in api package

package api

import (
	_ "github.com/jinzhu/gorm/dialects/sqlite"
	"github.com/labstack/echo/v4"
	"licence-server/model"
	"net/http"
)

< abridged>

func Create_a_Licence(c echo.Context) error {
	var CreateLicence model.Licence
	if err := c.Bind(CreateLicence); err != nil {
		return err
	}
	result := db.Create(&CreateLicence)
	return c.String(http.StatusOK, "Licence Created")
}
package middlewares

import (
	"github.com/jinzhu/gorm"
	"github.com/labstack/echo/v4"
)

// ContextDB : Inject db into echo Context
func ContextDB(db *gorm.DB) echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			c.Set("db", db)
			return next(c)
		}
	}
}

Any help appreciated

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions