Hello! GO is learning!
This time I would like to insert with gorm!
Data is api that I got last time Uses the data from.
The article that created the DB itself from GO is here.
Then I would like to start.
mysql.go
// root/app/models/fgi.go
package mysql
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
)
//SQLConnect DB connection
func SQLConnect() (database *gorm.DB, err error) {
DBMS := "mysql"
USER := "root"
PASS := ""
PROTOCOL := "tcp(localhost:3306)"
DBNAME := "table name"
CONNECT := USER + ":" + PASS + "@" + PROTOCOL + "/" + DBNAME + "?charset=utf8&parseTime=true&loc=Asia%2FTokyo"
return gorm.Open(DBMS, CONNECT)
}
Here, it is assumed that the DB has already been created. gorm is a GO ORM package.
In the SQLConnect () function, declare the DB information and
return gorm.Open(DBMS, CONNECT)
By doing so, it is connected to db. It may be better to summarize the DB information in Config etc. This time, we will do it as the root user.
fgi/fgi.go
This is the article introduced at the beginning It is a file of api that is getting in. I just got it in the above article, but here By doing json.Unmarshal, it is stored in the prepared structure.
The structure is here json-to-go You can easily prepare it on the site.
If you paste the api json on the left side, it will prepare the struct in the code.
package fgi
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
)
//APIClientFgi api information storage
type APIClientFgi struct {
key string
host string
httpClient *http.Client
}
//New struct generation
func New(key, host string) *APIClientFgi {
fgiClient := &APIClientFgi{key, host, &http.Client{}}
return fgiClient
}
//StructFgi fgi storage
type StructFgi struct {
Fgi struct {
Current struct {
Value int `json:"value"`
ValueText string `json:"valueText"`
} `json:"now"`
PreviousClose struct {
Value int `json:"value"`
ValueText string `json:"valueText"`
} `json:"previousClose"`
OneWeekAgo struct {
Value int `json:"value"`
ValueText string `json:"valueText"`
} `json:"oneWeekAgo"`
OneMonthAgo struct {
Value int `json:"value"`
ValueText string `json:"valueText"`
} `json:"oneMonthAgo"`
OneYearAgo struct {
Value int `json:"value"`
ValueText string `json:"valueText"`
} `json:"oneYearAgo"`
} `json:"fgi"`
}
//GetFgi api execution
func (fgi *APIClientFgi) GetFgi() (StructFgi, error) {
url := "https://fear-and-greed-index.p.rapidapi.com/v1/fgi"
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("x-rapidapi-host", fgi.host)
req.Header.Add("x-rapidapi-key", fgi.key)
res, err := http.DefaultClient.Do(req)
if err != nil {
return StructFgi{}, nil
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return StructFgi{}, nil
}
var fgiStruct StructFgi
if err := json.Unmarshal(body, &fgiStruct); err != nil {
log.Fatal(err)
}
return fgiStruct, nil
}
The struct generated by json-to-go is called and stored in the struct by json.Unmarshal.
models/fgi.go
In this file, the api information stored in the struct above is expanded and inserted into the DB.
package models
import (
"fmt"
"index-indicator-apis/mysql"
"time"
"index-indicator-apis/config"
"index-indicator-apis/fgi"
)
const (
tableNameFgis = "fgis"
)
//Fgis daily storage
type Fgis struct {
CreatedAt time.Time `json:"created_at,omitempty"`
NowValue int `json:"now_value,omitempty"`
NowText string `json:"now_text,omitempty"`
PcValue int `json:"pc_value,omitempty"`
PcText string `json:"pc_text,omitempty"`
OneWValue int `json:"one_w_value,omitempty"`
OneWText string `json:"one_w_text,omitempty"`
OneMValue int `json:"one_m_value,omitempty"`
OneMText string `json:"one_m_text,omitempty"`
OneYValue int `json:"one_y_value,omitempty"`
OneYText string `json:"one_y_text,omitempty"`
}
//initFgis migration
func initFgis() {
var err error
db, err := mysql.SQLConnect()
if err != nil {
panic(err.Error())
}
defer db.Close()
db.AutoMigrate(&Fgis{})
}
// NewFgis fgi.Receives StructFgi, converts it to Fgis and returns it
func NewFgis(f fgi.StructFgi) *Fgis {
createdAt := time.Now()
nowValue := f.Fgi.Current.Value
nowText := f.Fgi.Current.ValueText
pcValue := f.Fgi.PreviousClose.Value
pcText := f.Fgi.PreviousClose.ValueText
oneWValue := f.Fgi.OneWeekAgo.Value
oneWText := f.Fgi.OneWeekAgo.ValueText
oneMValue := f.Fgi.OneMonthAgo.Value
oneMText := f.Fgi.OneMonthAgo.ValueText
oneYValue := f.Fgi.OneYearAgo.Value
oneYText := f.Fgi.OneYearAgo.ValueText
return &Fgis{
createdAt,
nowValue,
nowText,
pcValue,
pcText,
oneWValue,
oneWText,
oneMValue,
oneMText,
oneYValue,
oneYText,
}
}
//Save Create New Fgis
func (f *Fgis) Create() error {
db, err := mysql.SQLConnect()
if err != nil {
panic(err.Error())
}
defer db.Close()
db.Create(&f)
return err
}
//After CreateNewFgis migration, hit api and save to db
func CreateNewFgis() error {
// initFgis() migration
fgiClient := fgi.New(config.Config.FgiAPIKey, config.Config.FgiAPIHost)
f, err := fgiClient.GetFgi()
if err != nil {
return err
}
fgi := NewFgis(f)
fmt.Println(fgi)
fmt.Println(fgi.Create())
return err
}
initFgis () uses the gorg method for migration.
Since the api information was stored in the struct earlier, it means preparing a struct that expands it and stores the expanded value.
db.AutoMigrate (& Fgis {})
This is the gorg method AutoMigrate method.
It will migrate the name of the structure prepared in advance as the table name. In this case
A table called fgis is created in mysql.
func NewFgis(f fgi.StructFgi) *Fgis{}
Here, the contents of StructFgi that stores api data are expanded and stored in the structure (migrated) prepared for INSERT.
func (f *Fgis) Create() error {}
In this method, after connecting to db with SQLConnect () of the function created in the mysql file
db.Create(&f)
By doing so, INSERT is realized. .Create is the method of gorm. By doing .Create (& struct), the information of the struct corresponding to the table name will be inserted.
Finally, the functions and methods prepared by CreateNewFgis ()
are executed.
I was able to execute this function safely by calling it from main.go.
that's all!