Structuring local imports without github in golang

I am creating a simple application and after reading the go application structuring document, I am still confused.

I want this structure:

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

app.go

Inside app.goI 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)
}

Models A and B are as follows:

package models

import "net/http"

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

Two questions:

  • What is the right way to import these files in the world? Do I really have to push them to github to be able to link to them? I understand that $ GOPATH is the namespace for the entire go workspace on the local machine. My $ GOPATH lists this directory.

  • Do I need to define the main method inside these files? Can I just export one function and it will be a processing function?

.

docs

+4
1

. .

$GOPATH/src.

  • $GOPATH

:

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

:

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

github.com, "github.com" .

- . , .

+5

Source: https://habr.com/ru/post/1672122/


All Articles