Quick Golang 0

Posted on September 2, 2022
Tags: codeetc
Concept Go JS Java
Dependencies go.mod package.json pom.xml
Autogen dependency go.sum package-lock.json

1 Quick Summary

{go package 1, go package 2} \(\in\) Go module
go packages are .go files
go module is the directory holding the
.go files

When calling functions from imported go packages remember: Lowercase function name is package-public
Uppercase function name is package-private

2 Go module

2.1 go.mod: Init root dir

mkdir projectFolder
cd projectFolder
go mod init github.com/UserJY/playGO

This will autogenerate go.mod file

  • github.com/UserJY/playGO is the name and the root directory of our module

2.2 go.sum: Download dependencies

go get -u github.com/gin-gonic/gin

This will autogenerate go.sum file

2.3 Explore go.mod go.sum

module github.com/UserJY/playGO

go 1.16

require (
	github.com/gin-gonic/gin v1.7.7 // indirect
  ...
	gopkg.in/yaml.v2 v2.4.0 // indirect
)

// indirect means your go project is not using the dependency.
go mod tidy after using the dependency to tidy it up.

github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
g
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
...

go.sum is just the transitive closure of dependencies.
Analogous to package.lock.json

3 Packages

3.1 main.go component/bleh.go

package main

import (
	"fmt"
	"github.com/UserJY/playGO/component" 
  //we import the DIRECTORY "component"
  //we do not import bleh.go or duhr
)

func main(){
	fmt.Println(duhr.Somefunc())

}

mkdir component Create component directory

package duhr

func Somefunc() int { // "S" in Somefunc() MUST BE CAPITALIZED
	return 2
}

ā€œSā€ in Somefunc() MUST BE CAPITALIZED since it is package-public
This allows main.go to use Somefunc()
duhr.somefunc() WILL FAIL since it is lowercase package-private

4 Running

try below (will fail because we are running locally)

go run .

# main.go:5:2: no required module provides package github.com/UserJY/playGO/bleh; to add it:
#         go get github.com/UserJY/playGO/bleh

To run locally:

go mod edit -replace github.com/UserJY/playGO/component=~/playGO/component

this will add replace github.com/UserJY/playGO/component => ~/playGO/component to your go.mod file