Harnessing Go Interfaces to Simulate Inheritance in a Messaging Bot Demo

Hey there, if you're diving into Go programming, you've probably noticed it skips traditional inheritance. But don't worry—interfaces step in to handle that polymorphism magic. Today, let's chat about how you can use them to create flexible, reusable code, all while building a simple bot for the LINE messaging platform. It's like giving your code superpowers without the class hierarchy hassle.

Why Interfaces Shine in Go for Inheritance-Like Behavior

Picture this: in languages like Java, you inherit methods from parent classes. Go flips the script by focusing on behaviors through interfaces. You define what something can do, and any type that implements those methods fits the bill. This keeps things lightweight and lets you mix and match functionalities effortlessly.

For instance, imagine you're crafting a bot that responds to user messages. Instead of rigid class structures, interfaces let you define a "Responder" that any component can adopt, making your bot adaptable to different scenarios.

Setting Up a Basic LINE Bot with Go

Before we get into the interface fun, let's sketch out the basics. You'll need the LINE Messaging API—grab your channel secret and access token from their developer console. We'll use Go's net/http package to handle webhooks, where LINE sends incoming messages.

Think of it as setting up a listener: your bot runs a server that catches messages and fires back replies. It's straightforward and powerful for real-time interactions.

Core Components of Our Bot

  • Webhook Handler: This catches POST requests from LINE and parses the events.
  • Message Processor: Analyzes the incoming text and decides on a response.
  • Reply Mechanism: Sends the crafted response back via the LINE API.

Implementing Interfaces for Flexible Responses

Here's where interfaces come alive. Let's define an interface called MessageHandler that outlines methods for processing and responding. Then, we can create different structs that implement it—like one for greetings and another for queries—mimicking inheritance by sharing behavior without direct extension.

This approach makes your code modular. Swap in new handlers without rewriting everything, perfect for expanding your bot's capabilities down the line.

And now, let's look at some code to bring this to life:

title: [Learning Notes][Golang] How to Achieve Inheritance Effects with Golang Interfaces - Using LINEbot to Connect to Different Databases as an Example
published: false
date: 2023-01-12 00:00:00 UTC
tags: 
canonical_url: http://www.evanlin.com/go-interfaces-inheritance/
---

![](http://www.evanlin.com/images/2022/0*gkZ1djQY5PA1u3wU.jpg)

# Preface

When preparing LINE Bot related sample code, I usually don't include a database. However, some sample code would benefit from storing data. Therefore, it's necessary to add database-related read and write operations.

Of course... there's also a "poor man's" version of a database. Since many services charge for their database services, there's a need for some workarounds. Using memory as a database setup.

So, how do you write the data processing logic only once in your code, and then use different databases for access depending on your deployment environment variables?

For example:

- If you have a PostgreSQL database URL, use the PG SQL related processing method.
- If not, use memory as the database.
- In the future, you can also add different cloud deployment methods (or support Firebase related databases).

This article will begin to describe how to achieve a similar inheritance effect through Golang's Interfaces. Using the same set of program logic code, you can read different databases based on your configured parameters.

# Sample Code: LINE Bot Group Chat Summary Generator

This time, I'm using the previous sample article [[Learning Document] LINE Bot Group Chat Summary Generator](https://www.evanlin.com/linebot-chatgpt/) as an example code. Let's first look at the overall structure.

#### Github Repo: https://github.com/kkdai/LINE-Bot-ChatSummarizer

## Data Structure Diagram

![image-20230113221237698](http://www.evanlin.com/images/2022/image-20230113221237698.png)

All implementations access related data through Data, which is the API of the Basic Class. As long as you create it, use the related Interfaces with different initial variables, and you can call the same processing information.

First, list the related processing code:

## Related Processing Code
<script src="https://gist.github.com/kkdai/62dc8354e7ce3e7607aeda0513513a58.js"></script>

Here, the implementation of `GroupDB` defined as Interfaces is used. Depending on different settings, `NewPGSql(url)` or `NewMemDB()` can make the corresponding implementation inside different.

## Detailed Listing of Different Database Development Methods

Next, list the implementation methods for different databases.

### Basic (Data)
<script src="https://gist.github.com/kkdai/e186c9ed2b088b3f30e5d2e9cee62668.js"></script>

This is the most basic setting. The most important thing is the declaration of the interface `GroupDB`, and then the other two must also have

- `ReadGroupInfo(string) GroupData`
- `AppendGroupInfo(string, MsgDetail)`

The implementation of the two functions, and the input parameters and output parameters must be the same. This way, you can use the same logic to operate on the data.

### Memory DB
<script src="https://gist.github.com/kkdai/7ff6487458ee8691b9ddf6993872186d.js"></script>

Next, this is the implementation of using Memory as the database. You can see that it mainly operates on related data processing through `map`. This way of using memory as a DB, if it is in FAAS (e.g. Heroku or Render.com), you will lose your stored data when the service sleeps.

### PostGresSQL DB
<script src="https://gist.github.com/kkdai/f1c4277ea2dfe7cabeb3a54e73aa7376.js"></script>

Next, this is the implementation of PostGresSQL. It mainly uses the version of the `"github.com/go-pg/pg/v10"` package, which can directly operate PostgresSQL through ORM, which can save a lot of trouble. But in many cases, not using SQL directly is actually more troublesome.

In the development process here, there is nothing to pay attention to. You only need to pay attention to the following implementations.

- `ReadGroupInfo(string) GroupData`
- `AppendGroupInfo(string, MsgDetail)`

![img](http://www.evanlin.com/images/2022/sum_all-20230116203414058.png)

## Future Development

Using Interfaces as a database access development method can be very convenient and leaves room for many future database resources. Whether it's supporting MongoDB or wanting to use MySQL, or even moving the entire database to FireStore, there's no need to change my original business logic. You only need to complete the basic database implementation.

I hope this article can give you some ideas.

Putting It All Together

With the interface in place, your main function can initialize handlers and route messages dynamically. It's like directing traffic: the interface ensures every handler speaks the same language, so your bot stays cohesive.

For more on LINE's setup, check out their official docs here. If you're new to Go, the Go documentation has great resources on interfaces.

There you have it—a fresh way to think about structuring your Go projects with interfaces, using a LINE bot as our playground. Experiment with it, and you'll see how it boosts your code's flexibility. Got questions? Drop them in the comments!