Fully-qualified import path in auto-generated code - go

My problem
My apologies if the problem is trivial - I'm fairly new to golang, and want to understand the imports mechanism. I use OSX and simple go programs compile and work well.
I've generated a golang server using automatic code generator in the swagger editor. I've unzipped the code into some directory in /tmp/, and the resulting server contains the following main.go file:
package main
import (
// WARNING!
// Change this to a fully-qualified import path
// once you place this file into your project.
// For example,
//
// sw "github.com/myname/myrepo/go"
//
sw "./go"
"log"
"net/http"
)
func main() {
log.Printf("Server started")
router := sw.NewRouter()
log.Fatal(http.ListenAndServe(":8080", router))
}
As expected from the comments, go build main.go Fails with the following error:
main.go:11:2:
go/default.go:3:1: expected 'IDENT', found 'import'
Forensics
The directory tree of the project
/tmp/goserver/go-server-server
├── LICENSE
├── api
│   └── swagger.yaml
├── go
│   ├── README.md
│   ├── app.yaml
│   ├── default.go
│   ├── logger.go
│   └── routers.go
└── main.go
go/default.go
package
import (
"net/http"
)
type Default struct {
}
func QuestionimagePost(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
}
What have I tried
Read about go packages
Tried to understand the package / import relationship in some github projects
Moved the directory tree to $GOPATH/src, and changed the import to sw "sw/go-server-server/go", which still gives main.go:13:2:
go/default.go:3:1: expected 'IDENT', found 'import'
What should be the fully-qualified import path of the sw import, and what does it mean?

The following did the trick:
Adding a package name to all .go files in the go folder (I used blah)
eg. in go/routers.go
package blah
import (
"log"
"net/http"
"time"
)
func Logger(inner http.Handler, name string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
inner.ServeHTTP(w, r)
log.Printf(
"%s %s %s %s",
r.Method,
r.RequestURI,
name,
time.Since(start),
)
})
}
Do the same for go/logger.go and, in your case, default.go
Following an go/routers.go:7:2: cannot find package "github.com/gorilla/mux" error, go get 'github.com/gorilla/mux'

You need to export some path as the GOPATH, say $HOME/go.
export GOPATH=$HOME/go.
Then you can put your project in $GOPATH/src/go-server-server ($HOME/go/src/go-server-server) and your fully qualified path would be go-server-server/go if I am reading everything correctly.

Related

Golang Fiber template engine HTML: render: template does not exist

On my Ubuntu 22.10 digitalocean server, I'm experimenting with Golang and Fiber and the html template engine. Loving it so far.
It all works, including the Mysql connection and sending email. Except for one thing.
I keep getting the error render: template index does not exist.
File system:
├── /gogo
├── main
├── main.go
├── go.mod
├── go.sum
├── /views
└── index.html
└── /public
└── plaatje.png
The code of my main.go:
package main
import (
"fmt"
"log"
fiber "github.com/gofiber/fiber/v2"
"github.com/gofiber/template/html"
)
func main() {
// Initialize standard Go html template engine
template_engine := html.New(
"./views",
".html",
)
// start fiber
app := fiber.New(fiber.Config{
Views: template_engine,
})
// add static folder
app.Static(
"/static", // mount address
"./public", // path to the file folder
)
// endpoint
app.Get("/", func(c *fiber.Ctx) error {
// Render index template
return c.Render("index", fiber.Map{
"Title": "It works",
"Plat": "almost",
})
})
log.Fatal(app.Listen(":9990"))
}
The index.html file:
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Unicode">
<title>{{.Title}}</title>
</head>
<body>
<h1>{{.Title}}</h1>
<p>{{.Plat}}</p>
<p><img src="./static/plaatje.png"></p>
</body>
</html>
When I run it locally on my Mac, it all works and the template is rendered as it should.
But on the Ubuntu server it all works except for the template, with the given error:
render: template index does not exist
I've tried changing ownership and permissions in Ubuntu: no results. However this is a bit of a blind spot for me, so this might still be the isue...
I've tried tinkering with the views path (./views, /views, views. etc): no results.
I've tried return c.Render("index.html", fiber.Map{: no results.
What am I missing?
The experiment with go run . gave a clue. When running it as a service, the mount point is not the dir where main is, but a path elsewhere on the server.
Changing...
template_engine := html.New(
"./views",
".html",
)
... with a relative path to an absolute path ...
template_engine := html.New(
"/home/username/go/views",
".html",
)
... solved the issue.
This issue is not mentioned in any source on this topic.

How to reference the struct in the same package

I am trying to build a web app with two files.
app.go and main.go are both in the same directory.
app.go
package main
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/mux"
)
type App struct {
Router *mux.Router
DB *sql.DB
}
func (a *App) Initialize(username, password, server, port, dbName, cacheAddr, cachePass string){
}
func (a *App) Run(addr string) {
}
main.go
package main
func main() {
a := App{}
// more code here
}
I thought my main.go file would recognize App{} but my editor is complaining that App is undeclared name
Both files are in the same main package but I am not sure what went wrong. Could anyone help me about it? Thank you!
From the comments I assume you run the following command: go run main.go. This will ONLY load code in main.go (and files included with import statements). To tell Go to load all .go files in the current directory, run the following instead:
go run .
Similarly, to tell VSCode to load alll files start it like this:
code .

Package: the importance of naming files when using initialization

I wrote a structure like display in the tree below.
.
├── README.md
├── db
│ └── db.go
├── go.mod
├── go.sum
├── handler
│ ├── category.go
│ ├── handler.go
│ └── users.go
├── main.go
├── model
│ ├── category.go
│ ├── model.go
│ └── users.go
└── route
├── category.go // init() ❌ error to using package vars
├── route.go // init() writing package vars
└── users.go // init() ✅ no error to using package vars
All the files in the packages except the one with the same name (route/route.go, handler/handler.go,...) are generated automatically. For these files to extend the package variables, I use golang's func init(){} ex:
route/route.go
package route
import (
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
var (
// public routes
e *echo.Echo = echo.New()
// restricted routes
r *echo.Group = e.Group("/restricted")
)
func init() {
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"http://localhost:3000"},
AllowMethods: []string{echo.GET, echo.PUT, echo.POST, echo.DELETE, echo.OPTIONS},
AllowHeaders: []string{echo.HeaderAuthorization, echo.HeaderContentType},
}))
e.Use(middleware.Recover())
r.Use(middleware.JWT([]byte("secret")))
}
route/category.go
package route
import (
"github.com/username/project/handler"
)
func init() {
r.GET("/category", handler.ListCategory)
r.POST("/category/add", handler.CreateCategory)
r.GET("/category/:id", handler.ReadCategory)
r.PUT("/category/edit/:id", handler.UpdateCategory)
r.DELETE("/category/:id", handler.DeleteCategory)
}
route/user.go
package route
import (
"github.com/username/project/handler"
)
func init() {
r.GET("/users", handler.ListUsers)
r.POST("/users/add", handler.CreateUser)
r.PUT("/users/edit/:id", handler.UpdateUser)
r.DELETE("/users/:id", handler.DeleteUser)
e.POST("/auth", handler.Login)
e.POST("/lost", handler.Lost)
e.POST("/password", handler.Password)
}
As you already understood, the category.go init() starts before the router.go init(), which is described here: Go Package initialization.
After coding a pretty program that auto writes routes like route/category.go. I realize that to solve this problem, I will have to rename router/router.go to router/0router.go (it works) so that it is still at the top of the pillar, but it's not a good approach.
Have any suggestions for this tree and the use of golang ini() ?
Thank you
Use variable declaration expressions to avoid file name dependencies. The assignments execute before the init() functions that reference the variables.
var (
// public routes
e *echo.Echo = newPublic()
// restricted routes
r *echo.Group = newRestricted()
)
func newPublic() *echo.Echo {
e := echo.New()
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"http://localhost:3000"},
AllowMethods: []string{echo.GET, echo.PUT, echo.POST, echo.DELETE, echo.OPTIONS},
AllowHeaders: []string{echo.HeaderAuthorization, echo.HeaderContentType},
}))
e.Use(middleware.Recover())
}
func newRestricted() *echo.Group {
r := e.Group("/restricted")
r.Use(middleware.JWT([]byte("secret")))
return r
}

Go lint complains the import when using dep

I saw the similar question here. But I couldn't solve my case.
I am having project initialised with dep and added the first dependency "Echo". Now folder structure looks like this
|--server
| |--server.go
|--vendor
|--main.go
The server.go has the following code
package server
import (
"net/http"
"github.com/labstack/echo"
)
// TestController : Test controller
func TestController(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
}
and the main.go has
package main
import (
"github.com/labstack/echo"
"github.com/sfkshan/pos/server"
)
func main() {
e := echo.New()
e.GET("/", server.TestController)
e.Logger.Fatal(e.Start(":1323"))
}
Now vscode shows the warning
cannot use server.TestController (type
func("github.com/sfkshan/pos/vendor/github.com/labstack/echo".Context)
error) as type "github.com/labstack/echo".HandlerFunc in argument to
e.GET
I am not sure why is this happening? If I delete the vendor folder folder the error vanishes. But again after running dep ensure (in this case vendor folder gets created which is expected) the error appears again.

How to set up http routing tests with templates in relative paths?

I'm writing a small web app with gorilla/mux. My folder structure inside my GOPATH is like this.
app/
- app.go
- views/
- layout.html
- login/
- login.go
- login_test.go
- login.html
I'd like to keep login as a completely separate package. Within login.go I initiate the template and render it on request. All file paths are relative to app.go as I run go run app.go in my main app/ folder.
package login
var view = template.Must(template.ParseFiles(
"login/login.html",
"views/layout.html",
))
func GetLogin(w http.ResponseWriter, r *http.Request) {
err := view.ExecuteTemplate(w, "layout", nil)
check(err)
}
That works fine and I can call the route in my app.go file.
import (
"github.com/zemirco/app/login"
)
func main() {
router := mux.NewRouter()
router.HandleFunc("/login", login.GetLogin).Methods("GET")
http.Handle("/", router)
http.ListenAndServe(":"+os.Getenv("PORT"), nil)
}
My problem is testing this route. Within login_test.go I have something like this.
package login
import (
"net/http"
"net/http/httptest"
"testing"
"."
)
func TestHandleGetLogin(t *testing.T) {
request, _ := http.NewRequest("GET", "/", nil)
response := httptest.NewRecorder()
login.GetLogin(response, request)
t.Log(response)
}
Whenever I run go test login/login_test.go I get the error message
open login/login.html: no such file or directory
As far as I know go test executes from within the login/ directory and therefore cannot find the html files. The relative file paths are wrong.
How can I solve this problem or what would be a better directory structure?

Resources