douzhonglong3789 2017-03-13 01:07
浏览 376
已采纳

在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 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 (
      "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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的