observer-bot/api.go

118 lines
2.6 KiB
Go

package main
import (
"encoding/json"
"fmt"
"git.gammaspectra.live/P2Pool/p2pool-observer/index"
"golang.org/x/exp/slices"
"io"
"net/http"
"net/url"
"strings"
"time"
)
func getFromAPI(host, method string) any {
uri, _ := url.Parse(host + method)
if response, err := http.DefaultClient.Do(&http.Request{
Method: "GET",
URL: uri,
}); err != nil {
return nil
} else {
defer response.Body.Close()
if response.StatusCode == http.StatusOK {
if strings.Index(response.Header.Get("content-type"), "/json") != -1 {
var result any
decoder := json.NewDecoder(response.Body)
decoder.UseNumber()
err = decoder.Decode(&result)
return result
} else if data, err := io.ReadAll(response.Body); err != nil {
return nil
} else {
return data
}
} else {
return nil
}
}
}
func getTypeFromAPI[T any](host, method string) *T {
uri, _ := url.Parse(host + method)
if response, err := http.DefaultClient.Do(&http.Request{
Method: "GET",
URL: uri,
}); err != nil {
return nil
} else {
defer response.Body.Close()
if response.StatusCode == http.StatusOK {
var result T
if data, err := io.ReadAll(response.Body); err != nil {
return nil
} else if json.Unmarshal(data, &result) != nil {
return nil
} else {
return &result
}
} else {
return nil
}
}
}
func getSideBlocksFromAPI(host, method string) []*index.SideBlock {
return getSliceFromAPI[*index.SideBlock](host, method)
}
func getSliceFromAPI[T any](host, method string) []T {
uri, _ := url.Parse(host + method)
if response, err := http.DefaultClient.Do(&http.Request{
Method: "GET",
URL: uri,
}); err != nil {
return nil
} else {
defer response.Body.Close()
if response.StatusCode == http.StatusOK {
var result []T
if data, err := io.ReadAll(response.Body); err != nil {
return nil
} else if json.Unmarshal(data, &result) != nil {
return nil
} else {
return result
}
} else {
return nil
}
}
}
func getPoolInfo(host string) map[string]any {
var basePoolInfo map[string]any
var ok bool
for {
d := getFromAPI(host, "/api/pool_info")
basePoolInfo, ok = d.(map[string]any)
if d == nil || !ok || basePoolInfo == nil || len(basePoolInfo) == 0 {
time.Sleep(5)
continue
}
break
}
return basePoolInfo
}
func getPreviousBlocks(host string) (result foundBlocks) {
result = getSliceFromAPI[*index.FoundBlock](host, fmt.Sprintf("/api/found_blocks?limit=%d", numberOfBlockHistoryToKeep))
//sort from oldest to newest
slices.SortFunc(result, func(a, b *index.FoundBlock) bool {
return a.MainBlock.Height < b.MainBlock.Height
})
return result
}