In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "Golang GinWeb framework how to use static files / templates to render", the article explains the content is simple and clear, easy to learn and understand, please follow the editor's ideas slowly in-depth, together to study and learn "Golang GinWeb framework how to use static files / templates to render" it!
Static file service
Package main import ("github.com/gin-gonic/gin"log"net/http"os") func main () {router: = gin.Default () cwd, _: = os.Getwd () / get the current file directory log.Printf ("current project path:% s", cwd) router.Static ("/ static", cwd) / / provide a static file server. The first parameter is the relative path. The second parameter is the root path, which generally places static files such as css,js,fonts. The front-end html uses relative paths such as / static/js/xxx or / static/css/xxx to reference router.StaticFS ("/ more_static", http.Dir (". /") / / to map the local file tree structure to the front end, and the local file system can be accessed through the browser. Simulated access: http://localhost:8080/more_static router.StaticFile ("/ logo.png", ". / resources/logo.png") / / StaticFile provides single static single file service, simulated access: http://localhost:8080/log.png / / Listen and serve on 0.0.0.0 resources/logo.png 8080 router.Run (": 8080")}
Return file data
Package main import ("github.com/gin-contrib/cors"github.com/gin-gonic/gin"net/http") func main () {router: = gin.Default () router.Use (cors.Default ()) router.GET ("/ local/file", func (c * gin.Context) {c.File (". / main.go")}) / / A FileSystem implements access to a collection of named files. / / The elements in a file path are separated by slash ('/', Utt002F) / / characters, regardless of host operating system convention. / / FileSystem interface, which requires a method to access files. The HTTP processor var fs http.FileSystem = http.Dir (". /") / / which provides the file access service root path / / takes the local directory as the file service root path router.GET ("/ fs/file", func (c * gin.Context) {c.FileFromFS ("main.go"). Fs) / / return the file data under the file service system}) router.Run (": 8080")} / * simulated access to file data: curl http://localhost:8080/local/file simulated access to file data under the file system: curl http://localhost:8080/fs/file * /
Provide file data service with file reader
Package main import ("github.com/gin-gonic/gin"net/http") func main () {router: = gin.Default () router.GET ("/ someDataFromReader", func (c * gin.Context) {response, err: = http.Get ("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png") if err! = nil | | response.StatusCode! = http.StatusOK {/ / when there is an error in the request link) Direct return service unavailable c.Status (http.StatusServiceUnavailable) return} reader: = response.Body / / construct a file reader defer reader.Close () contentLength: = response.ContentLength contentType: = response.Header.Get ("Content-Type") extraHeaders: = mapping [string] string {"Content-Disposition": `attachment Filename= "gopher.png" `,} / / DataFromReader writes the specified reader into the body stream and updates the HTTP code. / / func (c * Context) DataFromReader (code int, contentLength int64, contentType string, reader io.Reader, extraHeaders map [string] string) {} / / DataFromReader method writes the contents of the specified reader reader into the http response body flow, and updates the response code, response header information and other c.DataFromReader (http.StatusOK, contentLength, contentType, reader) ExtraHeaders)}) router.Run (": 8080")} / * Analog access: curl http://localhost:8080/someDataFromReader * /
HTML rendering
Use the LoadHTMLGlob () method or the LoadHTMLFiles () method
Package main import ("github.com/gin-gonic/gin"net/http") func main () {router: = gin.Default () / LoadHTMLGlob method loads the matching HTML file in glob mode, and combines router.LoadHTMLGlob ("templates/*") / / router.LoadHTMLFiles ("templates/template1.html", "templates/template2.html") router.GET ("/ index") with the HTML renderer Func (c * gin.Context) {/ / HTML method sets the response code, the template file name, the value in the rendering replacement template, and sets the response content type Content-Type "text/html" c.HTML (http.StatusOK, "index.tmpl", gin.H {"title": "Main website"). })}) router.Run (": 8080")} / * Simulation Test: curl http://localhost:8080/index * /
Add template file, templates/index.tmpl
{{.title}}
Template files that use the same file name in different folders
Func main () {router: = gin.Default () router.LoadHTMLGlob ("templates/**/*") router.GET ("/ posts/index", func (c * gin.Context) {c.HTML (http.StatusOK, "posts/index.tmpl", gin.H {"title": "Posts",}) router.GET ("/ users/index", func (c * gin.Context) {c.HTML (http.StatusOK) "users/index.tmpl", gin.H {"title": "Users",}) router.Run (": 8080")}
Add template files to the posts directory, templates/posts/index.tmpl
{{define "posts/index.tmpl"}} {{.title}}
Using posts/index.tmpl
{{end}}
Add template files to the users directory, templates/users/index.tmpl
{{define "users/index.tmpl"}} {{.title}}
Using users/index.tmpl
{{end}}
Custom template renderer
You can also use your custom HTML template renderer, which requires custom template files such as file1, file2, etc.
Package main import ("github.com/gin-gonic/gin"html/template"net/http") func main () {router: = gin.Default () / / template.ParseFiles (file 1, file 2.) Create a template object and then parse a set of templates The template and error are wrapped with the / / Must method using the file name as the template name. The memory address of the returned template is generally used for variable initialization, such as: var t = template.Must ("name"). Parse ("html") html: = template.Must (template.ParseFiles ("file1", "file2")) router.SetHTMLTemplate (html) / / associated template and HTML renderer router.GET ("/ index") Func (c * gin.Context) {/ / HTML method sets the response code, the name of the template file, the value in the rendering replacement template, and sets the response content type Content-Type "text/html" c.HTML (http.StatusOK, "file1", gin.H {"title": "Main website",}) router.Run (": 8080")}
Custom delimiter
You can customize the delimiter. The default delimiter in the template is {{}}, or we can modify it, such as adding a pair of square brackets below.
R: = gin.Default () r.Delims ("{[{", "}]}") r.LoadHTMLGlob ("/ path/to/templates")
Custom template method
See the sample code for details.
The template method is defined in both the template and the back end, which is executed when the template is rendered, similar to a filter method, such as a time formatting operation.
Package main import ("fmt"html/template"net/http"time"github.com/gin-gonic/gin") func formatAsDate (t time.Time) string {year, month, day: = t.Date () / / Date method returns year, month, day return fmt.Sprintf ("% dd/d", year, month) Day) / / format time} func main () {router: = gin.Default () router.Delims ("{[{", "}]}") / / the left and right delimiter / / SetFuncMap method in the custom template is set to the Gin engine with the given template.FuncMap, and the method / / FuncMap with the same name is called when the template is rendered. Each method must return one value or two values, the second of which is the error type router.SetFuncMap (template.FuncMap {"formatAsDate": formatAsDate,}) router.LoadHTMLFiles (". / testdata/template/raw.tmpl") / / loads a single template file and associates router.GET ("/ raw", func (c * gin.Context) {c.HTML (http.StatusOK, "raw.tmpl") with the HTML renderer Gin.H {"now": time.Date (2017, 07, 01, 0, 0, 0, time.UTC),}) router.Run (": 8080")} / * Simulation Test: curl http://localhost:8080/raw * /
Define template file: raw.tmpl
Date: {[{.now | formatAsDate}]}
Time formatting result:
Date: 2017-07-01
Multiple templat
Gin uses only one html.Template template engine by default, or you can refer to the multi-template renderer to use block-level template block template features similar to Go1.6.
For more information about the template, please see the official template package.
Thank you for your reading, the above is the "Golang GinWeb framework how to use static files / templates to render" content, after the study of this article, I believe you on the Golang GinWeb framework how to use static files / templates to render this problem has a deeper understanding, the specific use of the situation also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.