golang - creating, publishing and consuming a module

 To create a module, I have the following directory/folder layout




In my root go.mod - the code looks like this 

module github.com/mitzenjeremywoo/myfirstgolibrary

go 1.20


And the math.go code


package math

func Add(x int, y int) int {
    return x + y
}

func Minus(x int, y int) int {
    return x - y
}

Try to compile and once everything looks good, we will publish it.

To publish it 

git tag v1.0.3

git push origin v1.0.3


The consuming app 

You can use the following code below to consume the module above. You might need to run 

go mod init myapp

go get github.com/mitzenjeremywoo/myfirstgolibrary

You can use the following code to call the Math.Add and Math.Minus function.

package main

import (
    "fmt"

    m "github.com/mitzenjeremywoo/myfirstgolibrary/math"
)

func main() {
    fmt.Println("test test ")
    fmt.Println(m.Add(10, 20))
    fmt.Println(m.Minus(20, 20))
}

Also ensure that the app has the following go.mod

module myapp

go 1.20

require github.com/mitzenjeremywoo/myfirstgolibrary v1.0.3 // indirect


What if you would like to introduce v2 versioning to your module. Then perhaps your mod need to be change to include this 

Notice we have /v2 at the moment

module github.com/mitzenjeremywoo/myfirstgolibrary/v2

go 1.20

Then we would need to tag this to v2.0.0 and increment it accordingly. Otherwise go don't like it if we are still on version 1 - v1.0.4 that would not work. 

In the consuming app, you can use the following code, notice the library path becomes "github.com/mitzenjeremywoo/myfirstgolibrary/v2/math" with extra v2


package main

import (
    "fmt"

    m "github.com/mitzenjeremywoo/myfirstgolibrary/v2/math"
)

func main() {
    fmt.Println("tes ")
    fmt.Println(m.Add(10, 20))
    fmt.Println(m.Minus(20, 20))

}


Complete code.

https://github.com/mitzenjeremywoo/myfirstgolibrary

Comments

Popular posts from this blog

The specified initialization vector (IV) does not match the block size for this algorithm