gpt4 book ai didi

go - 如何从子目录中的 Controller 调用函数 - Golang

转载 作者:数据小太阳 更新时间:2023-10-29 03:45:13 24 4
gpt4 key购买 nike

我正在尝试制作一个网络应用程序,但不使用像 Revel 这样的框架,而只使用 Gorilla 工具包,

到目前为止,我的应用程序结构如下:

/App
- Controllers
- Index.go
- Views
- Index.html
- Public
- css
- js
- img
- main.go

我的 main.go 看起来像:

package main

import (
"github.com/gorilla/mux"
"net/http"
)

func main() {

r := mux.NewRouter()

r.HandleFunc("/", Index)

http.Handle("/", r)

http.ListenAndServe(":8080", nil)
}

Index.go 看起来像

package main

import (
"fmt"
"net/http"
)

func Index(res http.ResponseWriter, req *http.Request) {
fmt.Println("Here")
}

但是当我 go run main.go 时它说 Index is undefined,我不确定如何从子目录中的另一个文件调用函数。任何信息都将非常感谢。

最佳答案

Go 惯例阻止了这种情况。您必须将 Index() 保留在主包中。

一旦你有了一些可以分离出来的代码,你就可以创建一个子目录(包)并将其导入到主目录中。

https://golang.org/doc/effective_go.html

关于go - 如何从子目录中的 Controller 调用函数 - Golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27895439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com