How to make templates work with gin framework? - go

I am newbie to golang.
To learn it I have started with a simple web app using gin framework.
I have followed the gin doc & configured template file but not able to make it work. I am getting an error -
panic: html/template: pattern matches no files: `templates/*`
goroutine 1 [running]:
html/template.Must
/usr/local/Cellar/go/1.5.2/libexec/src/html/template/template.go:330
github.com/gin-gonic/gin.(*Engine).LoadHTMLGlob
/Users/ameypatil/deployment/go/src/github.com/gin-gonic/gin/gin.go:126
main.main()
/Users/ameypatil/deployment/go/src/github.com/ameykpatil/gospike/main.go:17
Below is my code -
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
//os.Setenv("GIN_MODE", "release")
//gin.SetMode(gin.ReleaseMode)
// Creates a gin router with default middleware:
// logger and recovery (crash-free) middleware
router := gin.Default()
router.LoadHTMLGlob("templates/*")
//router.LoadHTMLFiles("templates/index.tmpl")
router.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", gin.H{
"title": "GoSpike",
})
})
// By default it serves on :8080 unless a
// PORT environment variable was defined.
router.Run(":4848")
}
My directory structure is
- gospike
--- templates
------index.tmpl
--- main.go
go install command does not give any error
but on actually running, it gives the above error. I searched & there were similar issues logged on gin's github repo but they are closed now.
I have tried various things but I guess I am missing something obvious. What am I missing?

I'm guessing the issue is that you're using a relative filepath to access your templates.
If I compile and run your code from the gospike directory, it works fine. But if I run gospike from any other directory, I get the same error you were seeing.
So either you need to always run gospike in the parent directory of templates, or you need to use the absolute path. You could either hard code it:
router.LoadHTMLGlob("/go/src/github.com/ameykpatil/gospike/templates/*")
or you could do something like
router.LoadHTMLGlob(filepath.Join(os.Getenv("GOPATH"),
"src/github.com/ameykpatil/gospike/templates/*"))
but that will fail if you have multiple paths set in your GOPATH. A better long-term solution might be setting a special environment variable like TMPL_DIR, and then just using that:
router.LoadHTMLGlob(filepath.Join(os.Getenv("TMPL_DIR"), "*"))

use relative path glob will working, you can try to code
router.LoadHTMLGlob("./templates/*")
notice the . dot sign which meaning current directory, gin.Engine will load template
base on templates subdirectory of current directory .

Here is how I do it. This walks through the directory and collects the files marked with my template suffix which is .html & then I just include all of those. I haven't seen this answer anywhere so I thought Id post it.
// START UP THE ROUTER
router := gin.Default()
var files []string
filepath.Walk("./views", func(path string, info os.FileInfo, err error) error {
if strings.HasSuffix(path, ".html") {
files = append(files, path)
}
return nil
})
router.LoadHTMLFiles(files...)
// SERVE STATICS
router.Use(static.Serve("/css", static.LocalFile("./css", true)))
router.Use(static.Serve("/js", static.LocalFile("./js", true)))
router.Use(static.Serve("/images", static.LocalFile("./images", true)))
routers.LoadBaseRoutes(router)
routers.LoadBlog(router)
router.Run(":8080")

There is a multitemplate HTML render to support multi tempaltes.
You can use AddFromFiles to add multi files:
r.AddFromFiles("index", "templates/base.html", "templates/index.html")
r.AddFromFiles("article", "templates/base.html", "templates/index.html", "templates/article.html")
Or load multi files under a directory:
package main
import (
"path/filepath"
"github.com/gin-contrib/multitemplate"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.New()
r.HTMLRender = loadTemplates()
// ...
}
func loadTemplates() multitemplate.Render {
files, err := filepath.Glob("template/*.tmpl")
if err != nil {
panic("failed to load html templates: " + err.Error())
}
r := multitemplate.New()
// Generate our templates map from our template/ directories
for _, file := range files {
r.AddFromFiles(filepath.Base(file), file)
}
// add other html templates directly
r.Add("test.tmpl", someTemplate)
return r
}
You could see more APIs in this repo you want, hope this post help :)

Related

How to serve static files from all routes except one in Gin? [duplicate]

This question already has answers here:
Gin router: path segment conflicts with existing wildcard
(2 answers)
Closed 9 months ago.
As the title says, consider a Gin router where I want to serve static files from all routes except one. Let's say this one route is /api. A first attempt might look like this:
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.StaticFS("/", gin.Dir("static", false))
r.GET("/api/v1/foo", func(c *gin.Context) { c.JSON(200, gin.H{"foo": true}) })
r.Run(":9955")
}
The RouterGroup.StaticFS (and Static too) under the hood joins the relative path with a wildcard path param: path.Join(relativePath, "/*filepath"). When relativePath is the root path /, it will panic with:
panic: '/api/v1/foo' in new path '/api/v1/foo' conflicts with existing wildcard '/*filepath' in existing prefix '/*filepath'
This is due to Gin's http router implementation: routing matches on the path prefix, so a wildcard on root will conflict with every other route. More details about this behavior can be found here — which is where this question was raised.
Another possible solution is to prefix the static file route, so that it doesn't conflict with /api:
r.StaticFS("/static", gin.Dir("static", false))
but this doesn't allow me to serve assets from root too. How can I have a wildcard, or equivalent, on root and still match on one specific path?
There is a package called static for this.
https://github.com/gin-contrib/static#canonical-example
just modify the example as follows
package main
import (
"github.com/gin-contrib/static"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
// server a directory called static
r.Use(static.Serve("/", static.LocalFile("static", false)))
// And any route as usual
r.GET("/api/ping", func(c *gin.Context) {
c.String(200, "ping")
})
r.Run(":9955")
}

passing named parameters to index template while using httprouter golang package

I just learnt how to use the httprouter go package and read many documents about it but
failed to use the :name style of passing paramenters toe templates when it comes to the index
page template.
ex.
My router code:
func getRouter() *httprouter.Router {
// Load and parse templates (from binary or disk)
templateBox = rice.MustFindBox("templates")
templateBox.Walk("", newTemplate)
// mux handler
router := httprouter.New()
// Example route that encounters an error
router.GET("/broken/handler", broken)
// Index route
router.GET("/:email", index)
router.GET("/read/all", readingHandler)
router.POST("/submit/newcon", Handler1)
router.POST("/read/newcon", Handler2)
// Serve static assets via the "static" directory
fs := rice.MustFindBox("static").HTTPBox()
router.ServeFiles("/static/*filepath", fs)
return router
}
Then i get this error:
panic: wildcard segment ':email' conflicts with existing children in path '/:email'
so it should work with /user/:email instead of just /:email.

Problems running binary created by Go build

I have a simple Go application, it has a few template files where I render some text. After I build my binary with Go build I try to run the file and I get the error:
panic: html/template: pattern matches no files: public/*.html
I am using the Echo framework and have followed their steps on adding a render for templates.
Here is the code in my main.go file
// TemplateRenderer is a custom html/template renderer for Echo framework
type TemplateRenderer struct {
templates *template.Template
}
// Render renders a template document
func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
return t.templates.ExecuteTemplate(w, name, data)
}
func main() {
// Create a new instance of Echo
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())
renderer := &TemplateRenderer{
templates: template.Must(template.ParseGlob("public/*.html")),
}
e.Renderer = renderer
e.GET("/", func(context echo.Context) error {
return context.Render(http.StatusOK, "index.html", api.FetchCoinList())
})
}
Is there something I have to do to package my templates up in the binary? It works perfectly when I run go run main.go
Is there something I have to do to package my templates up in the binary?
Yes, make them avialable at the same (relative) folder where they are present when you run them with go run main.go.
For example if there is a public folder containing the templates next to your main.go, then make sure you "copy" the public folder next to your executable binary.
Read this question+answer for more options: how to reference a relative file from code and tests
Usually you should provide ways to define where to get static assets and files from. The app may have a default place to look for them, but it should be easy to change this setting (e.g. via command line flags, via environment variables or via config files).
Another option is to include static files in the executable binary. Check out this question how to do that: What's the best way to bundle static resources in a Go program?

Golang best way of calling/invoking sub project

Im moving my project from PHP to Golang and I looking efficient way of calling/invoking/handling control to sub project main.go from src main.go, I want to pass control from
http://localhost/ => http://localhost/sub-project1/
http://localhost/ => http://localhost/sub-project2/
http://localhost/ => http://localhost/sub-projectn/
I'm new to Golang I don't know how to do it in best way, and my project structure is
src/
main.go
sub-project1/
main.go
sub-project2/
main.go
sub-projectn/
main.go
gitHub.com/
......
golang.org/
......
I'm using httprouter for routing, in main.go which is located under src contain following
package main
import ....
// homePageHandler
// contactPageHandler
// aboutPageHandler
// loginPageHandler
// signupPageHandler
func main() {
router := httprouter.New()
router.GET("/", homePageHandler)
router.GET("/contact", contactPageHandler)
router.GET("/about", aboutPageHandler)
router.GET("/login", loginPageHandler)
router.GET("/signup", signupPageHandler)
// here I want to pass control to my sub project main.go
// and I don't want to write any /sub-project routing urls here,
// because each /sub-project's contain many urls
router.GET("/sub-project1", ??????)
router.GET("/sub-project2", ??????)
router.GET("/sub-project3", ??????)
router.GET("/sub-projectn", ??????)
}
and all files must be passes from src main.go because whole project has only one main() and inside any /sub-projectx main.go I want to do this
package main
import ....
// subprojectPageHandler
// feature1PageHandler
// feature2PageHandler
// feature3PageHandler
// ........
// featurenPageHandler
func main() {
router := httprouter.New()
router.GET("/sub-projectx", subprojectPageHandler)
router.GET("/sub-projectx/feature1", feature1PageHandler)
router.GET("/sub-projectx/feature2", feature2PageHandler)
router.GET("/sub-projectx/feature3", feature3PageHandler)
..........
router.GET("/sub-projectx/featureN", featureNPageHandler)
// here I want to pass control to my sub project main.go
// and I don't want to write any /sub-project routing urls here,
// because each /sub-project's contain many urls
router.GET("/sub-project1", ??????)
router.GET("/sub-project2", ??????)
router.GET("/sub-project3", ??????)
router.GET("/sub-projectn", ??????)
}
To be
Golang source code is not running through interpreter, but is built into a binary, which gives less flexibility in case of dynamic projects. That said, I'd keep my projects isolated one from another, and would let Nginx (for example) take care of multiple project grouping. Of course, that would require some refactoring like creating shared packages, etc.
Or not to be
If, for some reason, you still think running multiple projects via single binary is ok, it's your choice. In this case you might have a look into route grouping that are available in some frameworks. Here's what Go Gin provides:
func main() {
router := gin.Default()
// Simple group: v1
v1 := router.Group("/v1")
{
v1.POST("/login", loginEndpoint)
v1.POST("/submit", submitEndpoint)
v1.POST("/read", readEndpoint)
}
// Simple group: v2
v2 := router.Group("/v2")
{
v2.POST("/login", loginEndpoint)
v2.POST("/submit", submitEndpoint)
v2.POST("/read", readEndpoint)
}
router.Run(":8080")
}

How do I change the import file?

I have the following function in golang:
import (
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/aws/session"
"fmt"
)
func NewIAM() *SphinxIAM {
// awsConfig := aws.NewConfig()
sess, err := session.NewSession()
if err != nil {
fmt.Println("Failed to create session,", err)
return nil
}
session := &SphinxIAM{iam: iam.New(sess)}
return session
}
Now, I am getting the following error when I run this:
cannot use sess (type *session.Session) as type "github.com/aws/aws-sdk-go/aws/client".ConfigProvider in argument to iam.New:
*session.Session does not implement "github.com/aws/aws-sdk-go/aws/client".ConfigProvider (wrong type for ClientConfig method)
have ClientConfig(string, ...*"stash/cloud/sphinx/vendor/github.com/aws/aws-sdk-go/aws".Config) "stash/cloud/sphinx/vendor/github.com/aws/aws-sdk-go/aws/client".Config
want ClientConfig(string, ...*"github.com/aws/aws-sdk-go/aws".Config) "github.com/aws/aws-sdk-go/aws/client".Config
I have to change the method getting imported but how do I exactly do that?
Thanks!
The problem here is that your github.com/aws/aws-sdk-go/aws/session package is vendored, it is loaded from the folder stash/cloud/sphinx/vendor/github.com/aws/aws-sdk-go/aws.
But the function you want to pass it: iam.New() is not vendored, it does not come from the same vendor folder (stash/cloud/sphinx/vendor/xxx) but it comes directly from github.com/aws/aws-sdk-go/service/iam.
Either put both packages under the same vendor folder, or none. It is possible that one of your dependency tool does this, (e.g. glide), in which case you should instruct your tool to handle both as vendored.

Resources