如何在解析文件时停止代码的重复?

huangapple go评论75阅读模式
英文:

How to stop the repetition of code when parsing files

问题

我在每个函数中重复了相同的HTML文件代码。我只是在每个函数中更改了一个文件的名称,即indexHandler()中的ui/html/home.htmlsignup()中的ui/html/signup.html

其他文件名相同,并且ParseFiles()函数的代码在每个函数中也是相同的。如何防止代码在每次重复时重复。

func indexHandler(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != "/" {
        http.NotFound(w, r)
        return
    }

    files := []string{"ui/html/home.html", "ui/html/footer.html", "ui/html/base.html"}    
    tmpl, err := template.ParseFiles(files...)
    if err != nil {
        panic(err)
    }
    tmpl.Execute(w, nil)
}

func signup(w http.ResponseWriter, r *http.Request) {
    files := []string{"ui/html/signup.html", "ui/html/footer.html", "ui/html/base.html"}
    tmpl, err := template.ParseFiles(files...)
    if err != nil {
        panic(err)
    }
    tmpl.Execute(w, nil)
}    

func main() {
    http.HandleFunc("/", indexHandler)
    http.HandleFunc("/signup", signup)
    log.Println("Starting the server at :4000")
    http.ListenAndServe(":4000", nil)
}
英文:

I am repeating the same code of html files in every function. I just changed the name of one file in every function and that is ui/html/home.html in indexHandler() and ui/html/signup.html in signup()

Other file names are the same and the code of ParseFiles() is also the same in each function. How to prevent the code from repeating every time.

func indexHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}

	files := []string{"ui/html/home.html", "ui/html/footer.html", "ui/html/base.html",}    
	tmpl, err := template.ParseFiles(files...)
	if err != nil {
		panic(err)
	}
	tmpl.Execute(w, nil)
}

func signup(w http.ResponseWriter, r *http.Request) {
	files := []string{"ui/html/signup.html", "ui/html/footer.html", "ui/html/base.html",}
	tmpl, err := template.ParseFiles(files...)
	if err != nil {
		panic(err)
	}
	tmpl.Execute(w, nil)
}    

func main() {
	http.HandleFunc("/", indexHandler)
	http.HandleFunc("/signup", signup)
	log.Println("Starting the server at :4000")
	http.ListenAndServe(":4000", nil)
}

答案1

得分: 1

你可以将其设置为包变量。

package main

import (
	"fmt"
)

var (
	files = []string{"ui/html/home.html", "ui/html/footer.html", "ui/html/base.html"}
)

func indexHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}

	tmpl, err := template.ParseFiles(files...)
	if err != nil {
		panic(err)
	}
	tmpl.Execute(w, nil)
}

func signup(w http.ResponseWriter, r *http.Request) {
	tmpl, err := template.ParseFiles(files...)
	if err != nil {
		panic(err)
	}
	tmpl.Execute(w, nil)
}

func main() {
	http.HandleFunc("/", indexHandler)
	http.HandleFunc("/signup", signup)
	log.Println("Starting the server at :4000")
	http.ListenAndServe(":4000", nil)
}

如果你需要为特定的处理程序添加模板,可以创建一个新的切片,并将其附加到全局变量中。

tmpl, err := template.ParseFiles(append(files, []string{"..."}...)...)

我认为你需要阅读一些关于Go的有效编程的内容,可以参考https://golang.org/doc/effective_go#initialization 或者Go之旅https://tour.golang.org/welcome/1

一个应用的技巧是在初始化期间编译模板,而不是在请求处理期间。这将加快程序的运行速度。

package main 

//...

var (
	indexTpml = template.Must(template.ParseFiles(files...))
)

https://play.golang.org/p/TgjZYCul9M6

使用一些辅助函数,可以编写如下代码:

package main

import (
	"html/template"
	"log"
	"net/http"
)

func makeTpl(base string) *template.Template {
	files := []string{base, "ui/html/footer.html", "ui/html/base.html"}
	return template.Must(template.ParseFiles(files...))
}

var (
	indexTpml  = makeTpl("ui/html/home.html")
	signupTpml = makeTpl("ui/html/signup.html")
)

func indexHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}
	indexTpml.Execute(w, nil)
}

func signup(w http.ResponseWriter, r *http.Request) {
	signupTpml.Execute(w, nil)
}

func main() {
	http.HandleFunc("/", indexHandler)
	http.HandleFunc("/signup", signup)
	log.Println("Starting the server at :4000")
	http.ListenAndServe(":4000", nil)
}
英文:

You can make it a package variable.

https://play.golang.org/p/haDmat_kzkg

package main

import (
	"fmt"
)

var (
	files = []string{"ui/html/home.html", "ui/html/footer.html", "ui/html/base.html"}
)

func indexHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}

	tmpl, err := template.ParseFiles(files...)
	if err != nil {
		panic(err)
	}
	tmpl.Execute(w, nil)
}

func signup(w http.ResponseWriter, r *http.Request) {
	tmpl, err := template.ParseFiles(files...)
	if err != nil {
		panic(err)
	}
	tmpl.Execute(w, nil)
}

func main() {
	http.HandleFunc("/", indexHandler)
	http.HandleFunc("/signup", signup)
	log.Println("Starting the server at :4000")
	http.ListenAndServe(":4000", nil)
}

If you need to add a template for a specific handler, create a new slice out of the global variable and append to it.

tmpl, err := template.ParseFiles(append(files,[]string{"..."})...)

I think you have to read a bit about effective go in general, https://golang.org/doc/effective_go#initialization
or the go tour https://tour.golang.org/welcome/1

A tip to apply is to compile the template during initialization, rather during the request processing. This will speed up your program.

package main 

//...

var (
	indexTpml = template.Must(template.ParseFiles(files...))
)

https://play.golang.org/p/TgjZYCul9M6

Using some helper functions, one can write,

package main

import (
	"html/template"
	"log"
	"net/http"
)

func makeTpl(base string) *template.Template {
	files := []string{base, "ui/html/footer.html", "ui/html/base.html"}
	return template.Must(template.ParseFiles(files...))
}

var (
	indexTpml  = makeTpl("ui/html/home.html")
	signupTpml = makeTpl("ui/html/signup.html")
)

func indexHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}
	indexTpml.Execute(w, nil)
}

func signup(w http.ResponseWriter, r *http.Request) {
	signupTpml.Execute(w, nil)
}

func main() {
	http.HandleFunc("/", indexHandler)
	http.HandleFunc("/signup", signup)
	log.Println("Starting the server at :4000")
	http.ListenAndServe(":4000", nil)
}

huangapple
  • 本文由 发表于 2021年7月24日 17:24:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/68508665.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定