英文:
How to run the function from another file in golang?
问题
在这段代码中,我试图在浏览器中运行home
函数。我创建了两个文件,main.go
和handler.go
。在main.go
中,我调用了handler.Home
函数来运行它。但是它给我返回了一个空白页面。
当我将handler.go
文件中的Home()
函数复制到main.go
文件中时,它成功地运行了Home()
函数。
main.go
package main
import (
"fmt"
"net/http"
"github.com/ibilalkayy/WEBAPP1/handler"
)
func main() {
http.HandleFunc("/", handler.Home)
fmt.Println("Starting the server at :8080")
http.ListenAndServe(":8080", nil)
}
handler.go
package handler
import (
"html/template"
"net/http"
)
var tmpl = make(map[string]*template.Template)
func init() {
tmpl["home"] = template.Must(template.ParseFiles("templates/home.html", "templates/base.html"))
}
func Home(w http.ResponseWriter, r *http.Request) {
tmpl["home"].ExecuteTemplate(w, "home.html", nil)
}
仅包含main.go的版本
package main
import (
"fmt"
"html/template"
"net/http"
)
var tmpl = make(map[string]*template.Template)
func init() {
tmpl["home"] = template.Must(template.ParseFiles("templates/home.html", "templates/base.html"))
}
func home(w http.ResponseWriter, r *http.Request) {
tmpl["home"].ExecuteTemplate(w, "home.html", nil)
}
func main() {
http.HandleFunc("/", home)
fmt.Println("Starting the server at :8080")
http.ListenAndServe(":8080", nil)
}
以上是你要翻译的内容。
英文:
In this code, I am trying to run the home function in a browser. I made two files, main.go
and handler.go
. In main.go
I called the handler.Home
function to run it. But it gives me the blank page.
When I take the Home()
function from the handler.go
file and use it in main.go
file, it runs the Home()
function successfully.
main.go
package main
import (
"fmt"
"net/http"
"github.com/ibilalkayy/WEBAPP1/handler"
)
func main() {
http.HandleFunc("/", handler.Home)
fmt.Println("Starting the server at :8080")
http.ListenAndServe(":8080", nil)
}
handler.go
package handler
import (
"html/template"
"net/http"
)
var tmpl = make(map[string]*template.Template)
func init() {
tmpl["home"] = template.Must(template.ParseFiles("templates/home.html", "templates/base.html"))
}
func Home(w http.ResponseWriter, r *http.Request) {
tmpl["home"].ExecuteTemplate(w, "home.html", nil)
}
main.go only version
package main
import (
"fmt"
"html/template"
"net/http"
)
var tmpl = make(map[string]*template.Template)
func init() {
tmpl["home"] = template.Must(template.ParseFiles("templates/home.html", "templates/base.html"))
}
func home(w http.ResponseWriter, r *http.Request) {
tmpl["home"].ExecuteTemplate(w, "home.html", nil)
}
func main() {
http.HandleFunc("/", home)
fmt.Println("Starting the server at :8080")
http.ListenAndServe(":8080", nil)
}
答案1
得分: 1
我刚刚复制了你的代码,并创建了一个具有以下目录结构的处理程序包。
它按预期工作。
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论