dongyuan2652 2019-03-11 15:29
浏览 33
已采纳

解决非主包中的相对路径的问题

I'm having trouble resolving relative file paths in my Go application. For this app I decided to make a package that offers a uniform interface to the different configuration files. The conf package contains the relevant data files, so this is basically the file tree:

app/conf
    + config.go
    + config.json
    + ...
app/code
    + code.go
    + code_test.go

Problem is, when the tests defined in app/code/code_test.go calls a function in the app/conf package, which in turn tries to open app/conf/config.json, the relative path is messed up since the working directory is at app/code.

  • I've looked at other SO answers that mentions the path/filepath package and especially the filepath.Abs function for turning relative paths to absolute paths. However, this won't solve my problem since the absolute path will be based on the wrong working directory.

  • Some solution with "absolute paths" based on GOPATH would probably suffice, but I imagine the GOPATH would have little meaning when the code is built and exported.

  • Simply porting all configuration files to hard coded Go structs is not viable either as they're used cross-language.

  • 写回答

1条回答 默认 最新

  • duanhan5230 2019-03-11 16:20
    关注

    Relying on a config file path within your source is not only an issue in unit tests, but it will also be an issue in production. Typically, code would do something like this:

    • The config handler accepts an io.Reader which it will read configuration from.
    • main will open a file (whose path might be hard-coded, passed by command line, passed by env var, etc) and pass it to the config handler for reading.
    • Unit tests of the config handler will instead hard-code a config (or multiple configs, to test different scenarios) into something like bytes.Buffer and pass that to the config handler to read instead.
    • Unit tests of anything other than the code which reads the config file (so, anything that uses the configuration but does not manipulate it), would generate the Config struct in code rather than reading it from a real or fake file, as part of the test harness. For example, myConf := config.Config{SomeProp: "foo", OtherProp: true} and then pass that to the function under test.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP