🌊

【Go】DB操作を行うコンソールの開発始めます...!!

2024/08/07に公開

概要

Go(echo)による、DB操作を行うコンソール開発の記録残し。
※ ブログのネタに困ってきたのは内緒。

背景

現在担当しているプロジェクトにおいて、データベースへのユーザ登録や権限付与を行うためのコンソール開発が始まろうとしています。
インフラエンジニアですが、その開発工程に関わることができそうなので、キャッチアップも兼ねてGoで開発を行ってみようと思います。

やったこと

  • Goのインストール
brew install go
go mod init data-steward
  • echoのインストール
$ go get github.com/labstack/echo/v4
$ go get github.com/labstack/echo/v4/middleware
  • main.goの記述
package main

import (
	"log"
	"net/http"

	"github.com/labstack/echo/v4"
	"github.com/yyoosshh/data-steward/config"
)

func main() {
	// Load configuration
	cfg, err := config.Load()
	if err != nil {
		log.Fatalf("Failed to load configuration: %v", err)
	}

	// Initialize Echo instance
	e := echo.New()

	// Add a simple handler for the root path
	e.GET("/", func(c echo.Context) error {
		return c.JSON(http.StatusOK, map[string]string{"message": "Welcome to Data Steward"})
	})

	// Start server
	e.Logger.Fatal(e.Start(":" + cfg.Port))
}

  • config.go の記述
package config

import "github.com/spf13/viper"

type Config struct {
	Port     string
	DBDriver string
	DBSource string
}

func Load() (*Config, error) {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath(".")
	viper.AddConfigPath("./config")

	viper.SetDefault("port", "8080")
	viper.SetDefault("db_driver", "mysql")
	viper.SetDefault("db_source", "root:password@tcp(localhost:3306)/data_steward?parseTime=true")

	err := viper.ReadInConfig()
	if err != nil {
		return nil, err
	}

	var config Config
	err = viper.Unmarshal(&config)
	if err != nil {
		return nil, err
	}

	return &config, nil
}

  • config.yamlの記述
port: "8080"
db_driver: "mysql"
db_source: "root:password@tcp(localhost:3306)/data_steward?parseTime=true"
$ go run main.go

ここまでの作業で一旦、localhost:8080 に接続することでコンソール画面が表示されるようになりました!!
次は、コンソール画面周りの実装をしてみたいと思います。

GitHubで編集を提案

Discussion