I'm studying Golang.
--Hit Rakuten Rapid Api with Golang --Set APIKey in config.ini and call it from main.go file. --Furthermore, separate the function into another file and call it from the main.go file.
api We will use the API to get the FearAndGreed Index provided by Rakuten RapidApi.
There is no query and there is only one type of response.
config.ini config.go Create config.ini in the root directory and place api_key.
//config.ini
[fgi]
api_key = XXXXXXXXXXXXXXXXXXXXXX
api_host = XXXXXXXXXXXXXXXXXXXXXX
//config.go
package config
import (
"log"
"os"
"gopkg.in/ini.v1"
)
type ConfigList struct {
FgiAPIKey string
FgiAPIHost string
}
//Config global definition
var Config ConfigList
func init() {
cfg, err := ini.Load("config.ini")
if err != nil {
log.Printf("Failed to read file: %v", err)
os.Exit(1)
}
Config = ConfigList{
FgiAPIKey: cfg.Section("fgi").Key("api_key").String(),
FgiAPIHost: cfg.Section("fgi").Key("api_host").String(),
}
}
Create a struct and set the key and host of the config.ini file set earlier in ConfigList. Store as a string with .String ().
main.go
package main
import (
"fmt"
"io/ioutil"
"net/http"
"index-indicator-apis/config"
)
func main() {
url := "https://fear-and-greed-index.p.rapidapi.com/v1/fgi"
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("x-rapidapi-host", config.Config.FgiAPIHost)
req.Header.Add("x-rapidapi-key", config.Config.FgiAPIKey)
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
fmt.Println(string(body))
}
Get it with http.NewRequest of "net / http" and call the Key and Host of Config (ConfigList) created earlier with Header.Add.
Run in terminal
$ go run main.go
{"fgi":{"now":{"value":63,"valueText":"Greed"},"previousClose":{"value":56,"valueText":"Greed"},"oneWeekAgo":{"value":40,"valueText":"Fear"},"oneMonthAgo":{"value":56,"valueText":"Greed"},"oneYearAgo":{"value":83,"valueText":"Extreme Greed"}}}
I was able to get a response.
It seems that GO's design concept is to describe only the methods and functions that are executed more simply in the main.go file. So I created an fgi.go file and separated the functions.
// fgi.go
package fgi
import (
"fmt"
"io/ioutil"
"net/http"
"index-indicator-apis/config"
)
func DoRequest() {
url := "https://fear-and-greed-index.p.rapidapi.com/v1/fgi"
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("x-rapidapi-host", config.Config.FgiAPIHost)
req.Header.Add("x-rapidapi-key", config.Config.FgiAPIKey)
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
fmt.Println(string(body))
}
//main.go
package main
import "index-indicator-apis/fgi"
func main() {
fgi.DoRequest()
}
that's all! Next, I would like to make the function a method and pass arguments to it!
Recommended Posts