golang 自定義importpath


golang 的包導入和其他語言有好多不一樣的地方,以下是一個自定義的導入

golang 自定義導入說明

  • 一個官方的說明

    比較簡單,就不翻譯了,主要是說我們可以通過添加meta 數據告訴包如何進行加載

For example,
import "example.org/pkg/foo"
will result in the following requests:
 https://example.org/pkg/foo?go-get=1 (preferred)
 http://example.org/pkg/foo?go-get=1 (fallback, only with -insecure)
If that page contains the meta tag
 <meta name="go-import" content="example.org git https://code.org/r/p/exproj">
the go tool will verify that https://example.org/?go-get=1 contains the
same meta tag and then git clone https://code.org/r/p/exproj into
GOPATH/src/example.org.
  • 參考
package main
import (
    "log"
    // 自定義的地址,實際是從github 導入包

    "rongdemo.com"
)
func main() {
    log.Println(shortid.Generate())
}

具體操作

  • 修改hosts(我沒有rongdemo.com的域名),同時我使用的說本機
/etc/hosts
127.0.0.1       rongdemo.com
  • 添加一個靜態web站點,並添加meta 數據
yarn inti -y
yarn add live-server --dev
修改package.json
{
"name": "golang-web-package",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"devDependencies": {
"live-server": "^1.2.0"
},
"scripts": {
"start": "live-server"
}
}


nano index.html
<html>
<meta name="go-import" content="rongdemo.com git https://github.com/teris-io/shortid" />
<body>
golang package
</body>
</html>
  • 啟動&&使用dep 管理包
yarn start
dep init
  • 效果

參考實現

gopkg.in

實現原理也是類似的

參考資料

https://github.com/niemeyer/gopkg
https://golang.org/cmd/go/#hdr-Remote_import_paths
https://github.com/rongfengliang/golang-customimport

https://github.com/golang/gddo/wiki/Source-Code-Links


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM