douzhonglong3789
douzhonglong3789
2017-03-13 01:07

在golang中构建没有github的本地导入

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

app.go

Inside of app.go, I have the following:

package main

import (
    "net/http"

    // I have tried the following:
    "practice/models/a"
    "practice/models/b"
    "practice/models"
    "$GOPATH/practice/models/a"
    "$GOPATH/practice/models/b"
    "$GOPATH/practice/models"
    ...
)

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?

Thanks.

I have consulted the docs

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

1条回答

  • dongliyun3301 dongliyun3301 4年前

    See How to Write Go Code.

    Create your directory structure under $GOPATH/src.

    • $GOPATH
      • src
        • practice
          • models
          • routers

    Import the packages as follows:

    import (
      "practice/routers"
      "practice/models"
      ...
    )
    

    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 github.com, even if you use 'github.com' 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.

    点赞 评论 复制链接分享

为你推荐