Go-Lang-library-github

Go is a popular programming language that’s known for its simplicity and performance. One of its powerful features is the ability to quickly create reusable libraries that can help you abstract logic and use it across multiple projects. In this blog, we’ll walk through how to create and use a Go Library with a practical example: a JSON Helper library.

If you're looking to get started with GO language, this guide will help you to Set up GO Development Environment.

This tutorial will guide you through how to:

  1. Create a Go library, which exposes an interface to the implementation of JSON utility functions.
  2. Publish your library to GitHub.
  3. Set a version of the library.
  4. Use a Go library in your own projects.

Let’s dive in!

Setting Up Your Go Library

To get started with building our Go library, we need a project folder, where we initialize the Go module with go mod.

In the project directory, run:

go mod init github.com/your-username/json-helper-go

This creates a go.mod file which will manage the dependencies and versioning of your library.

Define the Interface

In this blog we are creating a library to work with JSON in Go. The library provides a set of utility functions to convert between JSON strings, structs, maps, and bytes.

package jsonhelper

type Helper interface {
    StringToStruct(s string, i interface{}) error
    StructToString(i interface{}) (string, error)
    StringToMap(s string) (map[string]interface{}, error)
    MapToString(m map[string]interface{}) (string, error)
    BytesToString(jsonBytes []byte) string
    StringToBytes(s string) []byte
    StructToBytes(i interface{}) (jsonBytes []byte, err error)
    BytesToStruct(b []byte, d interface{}) error
    ModifyInputJson(s string) (map[string]interface{}, error)
}

This interface outlines the functionality your JSON helper library will provide, making it easier for users to interact with JSON data in Go.

Implementing the JSON Helper Library

Now that we’ve defined our interface, let’s implement the functions in the jsonhelper package. Create a new file named json_helper.go in the jsonhelper package and add the following implementation:

package jsonhelper

import (
	"encoding/json"
	"errors"
)

type JsonHelper struct {}

func NewJsonHelper() Helper {
	return &JsonHelper{}
}

func (jh JsonHelper) StringToStruct(s string, i interface{}) error {
	return json.Unmarshal([]byte(s), i)
}

func (jh JsonHelper) StructToString(i interface{}) (string, error) {
	jsonBytes, err := json.Marshal(i)
	if err != nil {
		return "", err
	}
	return string(jsonBytes), nil
}

func (jh JsonHelper) StringToMap(s string) (map[string]interface{}, error) {
	var m map[string]interface{}
	err := json.Unmarshal([]byte(s), &m)
	if err != nil {
		return nil, err
	}
	return m, nil
}

func (jh JsonHelper) MapToString(m map[string]interface{}) (string, error) {
	jsonBytes, err := json.Marshal(m)
	if err != nil {
		return "", err
	}
	return string(jsonBytes), nil
}

func (jh JsonHelper) BytesToString(jsonBytes []byte) string {
	return string(jsonBytes)
}

func (jh JsonHelper) StringToBytes(s string) []byte {
	return []byte(s)
}

func (jh JsonHelper) StructToBytes(i interface{}) (jsonBytes []byte, err error) {
	return json.Marshal(i)
}

func (jh JsonHelper) BytesToStruct(b []byte, d interface{}) error {
	return json.Unmarshal(b, d)
}

func (jh JsonHelper) ModifyInputJson(s string) (map[string]interface{}, error) {
	var mapToProcess = make(map[string]interface{})
	err := json.Unmarshal([]byte(s), &mapToProcess)
	if err != nil {
		return nil, errors.New("cannot convert string to map")
	}
	mapToProcess["degree"] = "phd"
	return mapToProcess, nil
}

This code provides several utility functions for working with JSON, such as converting strings to structs, maps, and bytes, and modifying a JSON input.

Pushing Your Library to GitHub

To make our library available to others, we'll need to push it to a remote repository like GitHub.

  1. Create a new repository on GitHub (e.g. json-helper-go).
  2. Initialize git repo in the local project folder, i.e. git init.
  3. Link your local folder to the remote repository.
git remote add origin https://github.com/your-username/json-helper-go.git

Commit the change and push to remote repository,

git commit -m "Initial commit with JSON helper library"
git push origin master

Add a Version Number to Go Library

We have pushed the Go library implementation into github repository. Now we want to add different versions of the library. To add version numbers to your Go library, you can use Git tags to mark specific commits with version numbers. This is important for package versioning, especially if others use your library as a dependency.

To create a version tag, navigate to your local repository and run:

git tag v1.0.0

Replace v1.0.0 with the version number you want.

After tagging, push the tag to GitHub with:

git push origin v1.0.0

Using Your Go Library in a Project

Now that your library is published, let’s see how you can use it in another Go project.

In your new Go project, import the JSON helper library and use its functions:

Install the library in your project:

go get github.com/azam-akram/json-helper-go@v1.0.0

Use the library in your Go code:

package main

import (
	"fmt"
	jsonhelper "github.com/azam-akram/json-helper-go"
)

var empStr = `{
    "id": "The ID",
    "name": "The User",
    "designation": "CEO",
    "address":
    [
        {
            "doorNumber": 1,
            "street": "The office street 1",
            "city": "The office city 1",
            "country": "The office country 1"
        },
        {
            "doorNumber": 2,
            "street": "The home street 2",
            "city": "The home city 2",
            "country": "The home country 2"
        }
    ]
}`

func main() {
	jsonHelper := jsonhelper.NewJsonHelper()
	jsonHelper.StringToMap(empStr)

	fmt.Print(empStr)
}

In this example, we import the jsonhelper package, convert a JSON string to a struct, and modify a JSON string by adding new key-value pairs.

That's it!

Conclusion

In this blog, we’ve covered the entire process of creating a Go library, from defining the interface and implementation to pushing it to GitHub and using it in your own projects. With Go’s module system and simple syntax, writing reusable libraries is both efficient and effective.

Now you have a functional Go library that you can reuse and even share with the Go community!

© 2024 Solution Toolkit . All rights reserved.