Gin: why gin can't render js files?

Created on 10 Nov 2016  路  3Comments  路  Source: gin-gonic/gin

hi,I am new to gin. 锛﹚ant publish a html file,this file(upload.html) import some js files.but it dosn't work. if remove this js files,it works well. can anybody help me?
Excuse for my poor english!

func main(){    
    router := gin.Default()
    router.LoadHTMLGlob("templates/*")
//    router.LoadHTMLFiles("templates/upload.html")
    router.GET("/index",func(c *gin.Context){
        c.HTML(http.StatusOK, "upload.html", gin.H{
            "title": "Main website",
        })
    } )
    router.POST("/upload",uploadHandler)            
    router.Run(":8080")                       
}

Most helpful comment

@robvdl thanks

@kekemuyu i just fixed your example:

package main

import "gopkg.in/gin-gonic/gin.v1"

func main(){    
    router := gin.Default()

    router.Static("/assets", "./assets")

    router.LoadHTMLGlob("templates/*")
    //router.LoadHTMLFiles("templates/upload.html")
    router.GET("/index",func(c *gin.Context){
        c.HTML(http.StatusOK, "upload.html", gin.H{
            "title": "Main website",
        })
    } )
    router.POST("/upload",uploadHandler)            
    router.Run(":8080")                       
}

And finally fix your src in your HTML, pointing now everything to /assets/*.

Closing.

All 3 comments

You don't usually "render" JS files like templates, instead use something like the static middleware instead and put all your .js files in a folder usually called "public" in Go, or sometimes just "static".

Have a look at https://github.com/gin-gonic/contrib/tree/master/static

@robvdl thanks

@kekemuyu i just fixed your example:

package main

import "gopkg.in/gin-gonic/gin.v1"

func main(){    
    router := gin.Default()

    router.Static("/assets", "./assets")

    router.LoadHTMLGlob("templates/*")
    //router.LoadHTMLFiles("templates/upload.html")
    router.GET("/index",func(c *gin.Context){
        c.HTML(http.StatusOK, "upload.html", gin.H{
            "title": "Main website",
        })
    } )
    router.POST("/upload",uploadHandler)            
    router.Run(":8080")                       
}

And finally fix your src in your HTML, pointing now everything to /assets/*.

Closing.

Ah yes I remember now, the static middleware is only required if you want to serve static files from / instead of some sub url like /static (like when dealing with serving up SPAs), this has to do with Gin's router design based on httprouter.

Otherwise, router.Static() is enough :)

Was this page helpful?
0 / 5 - 0 ratings