dongyue9860
dongyue9860
采纳率100%
2018-11-19 06:28

如何在GO中访问另一个文件

已采纳

I'm trying to access a controller from main.go but I'm getting the following error:

./main.go:34:28: cannot refer to unexported name controllers.getUserDetails
./main.go:34:28: undefined: controllers.getUserDetails

here's a snippet of my main.go, I've removed some extra code

package main

import (
  "net/http"
  "os"
  "log"
  "github.com/urfave/negroni"
  "github.com/gorilla/mux"
  "github.com/joho/godotenv"
  "Go-Social/controllers"
 )

 func main() {
   router := mux.NewRouter()
   UserRouter := router.PathPrefix("/api/user").Subrouter()
   UserRouter.HandleFunc("", controllers.getUserDetails).Methods("GET")

   env := os.Getenv("GO_ENV")
   if "" == env {
    env = "Development"
   }

   // appending middlewares
   server := negroni.Classic()

   // router handler with negroni
   server.UseHandler(router)

   // starting server
   server.Run(":" + os.Getenv(env + "_PORT"))

 }

my controller.go file

package controllers

import (
  "net/http"
  "fmt"
)

func getUserDetails(w http.ResponseWriter, r *http.Request) {
  fmt.Println("here")
  message := "Hello World"
  w.Write([]byte(message))

}

Please Help I'm new to Go. Thanks in advance.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dou7466 dou7466 3年前

    to use a function from another package, you need to export it (GetUserDetails)

    as said here

    An identifier may be exported to permit access to it from another package

    func GetUserDetails(w http.ResponseWriter, r *http.Request) {
      fmt.Println("here")
      message := "Hello World"
      w.Write([]byte(message))
    }
    
    点赞 评论 复制链接分享
  • dongqin6926 dongqin6926 3年前

    Since the getUserDetails function is in another package it cannot be accessed. Only functions starting with capital letter can be accessed. That's how encapsulation works in Go.

    func GetUserDetails(w http.ResponseWriter, r *http.Request) {
      fmt.Println("here")
      message := "Hello World"
      w.Write([]byte(message))
    }
    

    So in your main:

    UserRouter.HandleFunc("", controllers.GetUserDetails).Methods("GET")
    

    Language like Java, enCAPSulation in class-based OOP is achieved through private and public class variables / methods. In Go, encapsulation is achieved on a package level.

    In other words, in Go, starting with capital letter for any package object (type, variable or function) will allow you to access it from another package.

    点赞 评论 复制链接分享