1
0
mirror of https://github.com/go-micro/go-micro.git synced 2024-12-12 08:23:58 +02:00
go-micro/plugins/config/source/url/url.go

72 lines
1.1 KiB
Go
Raw Normal View History

2020-12-26 17:32:45 +02:00
// Package url loads changesets from a url
package url
import (
"io"
2020-12-26 17:32:45 +02:00
"net/http"
"time"
2021-10-12 13:55:53 +02:00
"go-micro.dev/v4/config/source"
2020-12-26 17:32:45 +02:00
)
type urlSource struct {
url string
opts source.Options
}
var (
DefaultURL = "http://localhost:8080/config"
)
func (u *urlSource) Read() (*source.ChangeSet, error) {
rsp, err := http.Get(u.url)
if err != nil {
return nil, err
}
defer rsp.Body.Close()
b, err := io.ReadAll(rsp.Body)
2020-12-26 17:32:45 +02:00
if err != nil {
return nil, err
}
ft := format(rsp.Header.Get("Content-Type"))
if len(ft) == 0 {
ft = u.opts.Encoder.String()
}
cs := &source.ChangeSet{
Data: b,
Format: ft,
Timestamp: time.Now(),
Source: u.String(),
}
cs.Checksum = cs.Sum()
return cs, nil
}
func (u *urlSource) Watch() (source.Watcher, error) {
return newWatcher(u)
}
// Write is unsupported
func (u *urlSource) Write(cs *source.ChangeSet) error {
return nil
}
func (u *urlSource) String() string {
return "url"
}
func NewSource(opts ...source.Option) source.Source {
options := source.NewOptions(opts...)
url, ok := options.Context.Value(urlKey{}).(string)
if !ok {
url = DefaultURL
}
return &urlSource{url: url, opts: options}
}