问题描述
像npm一样,npm中的所有软件包都有一个索引文件-https://replicate.npmjs.com/_all_docs。我的问题是Go中也有这样的索引文件吗?
解决方法
位于https://index.golang.org/index的模块索引是通过https://proxy.golang.org获取的新模块版本的提要(两者的文档均为here)。它是可用的最全面的索引,但是考虑到proxy.golang.org的使用是可选的,因此它肯定是不完整的。
通过将since查询参数设置为上一个块中的最大时间戳,可以读取proxy.golang.org以2K块为单位的所有模块版本。
使用以下代码读取整个供稿:
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
type module struct {
Path,Version,Timestamp string
}
func chunk(since string) ([]module,error) {
resp,err := http.Get("https://index.golang.org/index?since=" + since)
if err != nil {
return nil,err
}
defer resp.Body.Close()
dec := json.NewDecoder(resp.Body)
var mods []module
for dec.More() {
var mod module
if err := dec.Decode(&mod); err != nil {
return nil,err
}
mods = append(mods,mod)
}
return mods,nil
}
func main() {
var lastMod module
for {
mods,err := chunk(lastMod.Timestamp)
if err != nil {
log.Fatal(err)
}
// We are done of there are no results.
if len(mods) == 0 {
return
}
// Last module in previous chunk can be returned in this chunk.
if mods[0] == lastMod {
mods = mods[1:]
}
// We are done of there are no results.
if len(mods) == 0 {
return
}
for _,m := range mods {
fmt.Println(m.Path,m.Version)
}
lastMod = mods[len(mods)-1]
}
}
,
据我所知,Go.dev提供了一个索引文件Go Module Index,但是我不确定它是否包含所有go模块。