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 thesame meta tag and then git clone https://code.org/r/p/exproj intoGOPATH/src/example.org.
package mainimport ( "log" // 自訂的地址,實際是從github 匯入包 "rongdemo.com")func main() { log.Println(shortid.Generate())}
具體操作
- 修改hosts(我沒有rongdemo.com的網域名稱),同時我使用的說本機
/etc/hosts127.0.0.1 rongdemo.com
yarn inti -yyarn 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>
yarn startdep init
參考實現
gopkg.in
實現原理也是類似的
參考資料
https://github.com/niemeyer/gopkg
https://golang.org/cmd/go/#hdr-Remote_import_paths
https://github.com/rongfengliang/golang-customimport