2017-03-13 01:07
浏览 256


I'm building a simple app and after reading the doc on structuring go applications, I'm still confused.

I want this structure:

  • practice
    • models (packaged as models)
      • a
      • b
    • routers (packaged as routers)
      • a
      • b


Inside of app.go, I have the following:

package main

import (

    // I have tried the following:

func main() {
    http.HandleFunc("/a", AHandler)
    http.HandleFunc("/b", BHandler)
    http.ListenAndServe(":8080", nil)

The A and B models look like this:

package models

import "net/http"

func AHandler(w http.ResponseWriter, r *http.Request) {
   // code

Two questions:

  1. What in the world is the right way to import these files? Do I really have to push them to github in order to be able to reference them? I understand the $GOPATH is the namespace for the entire go workspace on a local machine. My $GOPATH is set to include this directory.

  2. Do I need to define a main method inside of these files? Can I just export a single function and have that be the handling function?


I have consulted the docs

图片转代码服务由CSDN问答提供 功能建议

我正在构建一个简单的应用程序,在阅读了有关构建go应用程序的文档之后,我仍然感到困惑。 / p>


  • 练习
    • 模型(打包为模型)
      • a
      • b
      • 路由器(打包为路由器)
        • 一个
        • b'/ LI>


          app.go 里面,我有以下内容:

            package main 
          “ net / http” 
          “ practice / models / a” 
          “ practice / models / b” 
          “ $ GOPATH /实践/模型/ a” 
          “ $ GOPATH /实践/模型/ b” 
          “ $ GOPATH /实践/模型” 
           \  nfunc main(){
           http.HandleFunc(“ / a”,AHandler)
           http.HandleFunc(“ / b”,BHandler)
           <  / code>  


          导入“ net / http” 
          fun  c AHandler(w http.ResponseWriter,r * http.Request){

          两个问题: \ n

          1. 导入这些文件的正确方法是什么? 我是否真的必须将它们推送到github才能引用它们? 我知道$ GOPATH是本地计算机上整个go工作区的名称空间。 我的$ GOPATH设置为包括此目录。

          2. 我是否需要在这些文件中定义主要方法? 我可以仅导出一个函数并将其作为处理函数吗?


            I 已查阅文档

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongliyun3301 2017-03-13 01:17

    See How to Write Go Code.

    Create your directory structure under $GOPATH/src.

    • $GOPATH
      • src
        • practice
          • models
          • routers

    Import the packages as follows:

    import (

    Use the imported packages like this:

    func main() {
      http.HandleFunc("/a", models.AHandler)
      http.HandleFunc("/b", models.BHandler)
      http.ListenAndServe(":8080", nil)

    You do not need to push to, even if you use '' in the file path.

    The main function in the main package is the entry point for the application. Do not define main functions in packages other than main.

    打赏 评论

相关推荐 更多相似问题