代码拉取完成,页面将自动刷新
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2024-07-10
package resource
import (
"encoding/json"
"gitee.com/go-libs/config/src/common"
"gopkg.in/yaml.v3"
"os"
"reflect"
)
const NotfoundResource = Resource("")
// Resource
// is a type name for configuration file.
//
// f := config.Resource("./config/app.yaml")
// f := config.Resource("/data/sketch/config/app.yaml")
type Resource string
// Found
// return true if resource is existed.
func (o Resource) Found() bool {
return o != NotfoundResource
}
// Notfound
// return true if resource is empty.
func (o Resource) Notfound() bool {
return o == NotfoundResource
}
// Read
// reads resource content.
func (o Resource) Read() (data []byte, err error) {
if o.Found() {
data, err = os.ReadFile(o.String())
}
return
}
// ScanJson
// scans resource content of json to v.
func (o Resource) ScanJson(v any) (err error) {
var data []byte
// After scan.
defer func() {
if x, ok := v.(AfterScanner); ok {
x.After()
}
}()
// Before scan.
if x, ok := v.(BeforeScanner); ok {
x.Before()
}
// Read and unmarshal.
if data, err = o.ready(v); err == nil {
err = json.Unmarshal(data, v)
}
return
}
// ScanYaml
// scans resource content of yaml to v.
func (o Resource) ScanYaml(v any) (err error) {
var data []byte
// After scan.
defer func() {
if x, ok := v.(AfterScanner); ok {
x.After()
}
}()
// Before scan.
if x, ok := v.(BeforeScanner); ok {
x.Before()
}
// Read and unmarshal.
if data, err = o.ready(v); err == nil {
err = yaml.Unmarshal(data, v)
}
return
}
// String
// return resource name.
//
// return "/data/sketch/config/app.yaml"
func (o Resource) String() string {
return string(o)
}
// +---------------------------------------------------------------------------+
// | Access methods |
// +---------------------------------------------------------------------------+
func (o Resource) ready(v any) (data []byte, err error) {
ref := reflect.TypeOf(v)
// Return
// error if passed target v is not pointer.
if ref.Kind() != reflect.Pointer || ref.Elem().Kind() != reflect.Struct {
err = common.ErrTargetMustBePointerStruct
return
}
// Read
// resource content.
data, err = o.Read()
return
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。