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

71 lines
1.6 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/src/properties"
2024-07-02 03:02:57 -07:00
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
2022-08-05 12:07:35 -07:00
)
type Request struct {
props properties.Properties
2024-07-02 03:02:57 -07:00
env runtime.Environment
2022-08-05 12:07:35 -07:00
}
2024-07-02 03:02:57 -07:00
func (r *Request) Init(env runtime.Environment, props properties.Properties) {
2022-08-05 12:07:35 -07:00
r.env = env
r.props = props
}
2024-07-02 03:02:57 -07:00
func Do[a any](r *Request, url string, requestModifiers ...runtime.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 {
2023-01-16 11:58:43 -08:00
r.env.Error(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")
2023-01-16 11:58:43 -08:00
r.env.Error(err)
return data, err
}
2024-07-02 03:02:57 -07:00
func do[a any](r *Request, url string, body io.Reader, requestModifiers ...runtime.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 {
2023-01-16 11:58:43 -08:00
r.env.Error(err)
2022-08-05 12:07:35 -07:00
return data, err
}
err = json.Unmarshal(responseBody, &data)
if err != nil {
2023-01-16 11:58:43 -08:00
r.env.Error(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
}