Hacker News new | ask | show | jobs
by efiecho 2227 days ago
I have not yet been able to find a simple "Hello World" example of starting a new project with Go modules instead of $GOPATH.
3 comments

Hey there I found modules to be confusing coming from GOPATH too, but they're straight forward, super barebones example:

    #!/bin/bash

    cd $HOME

    # Create project directory
    mkdir hellogo

    cd hellogo

    # Init project modfile
    go mod init example.com/hellogo

    # Create the main source file
    # Uses bash's heredoc
    cat << EOF > ./main.go
    package main
    import "fmt"
    func main() {
        fmt.Print("Hello world")
    }
    EOF

    # Build it
    go build

    # Run it
    ./hellogo
You can also skip building, and run directly using `go run`!
Actually, the official Go Blog has a decent "Hello World" example[0] for go modules - I've used this before, had to double check. [0] https://blog.golang.org/using-go-modules
go mod init github.com/your/project

Then, go get -v will download your dependencies to GOPATH, and (re)generate go.mod, go.sum. For info on how to update dependencies, read `go help get`.

When using modules (presence of a valid go.mod file), GOPATH won't be used for resolving imports. So you don't have to actually work in GOPATH anymore, dependencies are just stored there.