oh-my-posh/src/http/request.go

71 lines
1.7 KiB
Go
Raw Normal View History

2022-08-05 12:07:35 -07:00
package http
import (
"encoding/json"
"errors"
"io"
2022-12-28 08:30:48 -08:00
"github.com/jandedobbeleer/oh-my-posh/platform"
"github.com/jandedobbeleer/oh-my-posh/properties"
2022-08-05 12:07:35 -07:00
)
type Request struct {
props properties.Properties
2022-11-09 11:27:54 -08:00
env platform.Environment
2022-08-05 12:07:35 -07:00
}
2022-11-09 11:27:54 -08:00
func (r *Request) Init(env platform.Environment, props properties.Properties) {
2022-08-05 12:07:35 -07:00
r.env = env
r.props = props
}
2022-11-09 11:27:54 -08:00
func Do[a any](r *Request, url string, requestModifiers ...platform.HTTPRequestModifier) (a, error) {
if data, err := getCacheValue[a](r, url); err == nil {
return data, nil
}
return do[a](r, url, nil, requestModifiers...)
2022-08-05 12:07:35 -07:00
}
func getCacheValue[a any](r *Request, key string) (a, error) {
2022-08-05 12:07:35 -07:00
var data a
cacheTimeout := r.props.GetInt(properties.CacheTimeout, 30)
if cacheTimeout <= 0 {
return data, errors.New("no cache needed")
2022-08-05 12:07:35 -07:00
}
if val, found := r.env.Cache().Get(key); found {
err := json.Unmarshal([]byte(val), &data)
if err != nil {
r.env.Error("OAuth", err)
2022-08-05 12:07:35 -07:00
return data, err
}
return data, nil
2022-08-05 12:07:35 -07:00
}
err := errors.New("no data in cache")
r.env.Error("OAuth", err)
return data, err
}
2022-11-09 11:27:54 -08:00
func do[a any](r *Request, url string, body io.Reader, requestModifiers ...platform.HTTPRequestModifier) (a, error) {
var data a
httpTimeout := r.props.GetInt(properties.HTTPTimeout, properties.DefaultHTTPTimeout)
2022-08-05 12:07:35 -07:00
responseBody, err := r.env.HTTPRequest(url, body, httpTimeout, requestModifiers...)
if err != nil {
r.env.Error("OAuth", err)
2022-08-05 12:07:35 -07:00
return data, err
}
err = json.Unmarshal(responseBody, &data)
if err != nil {
r.env.Error("OAuth", err)
2022-08-05 12:07:35 -07:00
return data, err
}
cacheTimeout := r.props.GetInt(properties.CacheTimeout, 30)
2022-08-05 12:07:35 -07:00
if cacheTimeout > 0 {
r.env.Cache().Set(url, string(responseBody), cacheTimeout)
}
return data, nil
}