func init()
을 사용할 수 있습니다. 패키지를 초기화하는 동안 프로그램 실행 직전에 호출되는 특수 함수입니다.
다음은 다른 mux 라이브러리를 사용하여 달성 할 수 있지만 gorilla/mux 라우터를 사용하여 원하는 것을 얻는 방법의 예입니다.
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
// main.go
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
var routes []Route
func registerRoute(route Route) {
routes = append(routes, route)
}
func main() {
router := mux.NewRouter().StrictSlash(false)
for _, route := range routes {
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(route.HandlerFunc)
}
if err := http.ListenAndServe(":8080", router); err != nil {
log.Fatalln(err)
}
}
// index.go
func init() {
registerRoute(Route{
"index",
"GET",
"/",
func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "welcome")
},
})
}
// users.go
func init() {
registerRoute(Route{
"listUsers",
"GET",
"/users",
listUsers,
})
}
func listUsers(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "users list")
}
// products.go
func init() {
registerRoute(Route{
"listProducts",
"GET",
"/products",
listProducts,
})
}
func listProducts(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "products list")
}
이 패턴은
database/sql
및
image
패키지가 예를 들어 golang 의해 사용된다. 이것에 대해 좀 더 자세히 읽을 수 있습니다 :
https://www.calhoun.io/why-we-import-packages-we-dont-actually-use-in-golang/
글쎄, (잘 모르겠지만) 글쎄, 당신의 문제를 이해하면,'func init()'이 당신이 찾고있는 것입니다. – Volker