草庐IT

go - 尝试使用本地子模块时出现问题

coder 2024-07-12 原文

我正在尝试将 go modules 与一些尚未推送到 github 的本地代码一起使用(golang 版本为 1.12.7)

到目前为止,我有 3 个模块,它们都在同一个父根目录(同级文件夹)下。 mapsgo-database-util已经被推送,但是模块应该使用我本地的任何东西(我还没有为 go-log-util 创建一个 git repo),所以我认为这不相关。

/maps
    go.mod
    go.sum
    main.go
    /api
        ...more files (just a regular package, not a module)

/go-database-util
    db.go
    go.mod
    go.sum

/go-log-util
    log.go
    go.mod
    go.sum

两者都是 go-database-utilgo-log-util是库,没有提供主包。有趣的是,go-database-util导入/maps/main.go 时工作正常,但尝试导入 go-log-util 时情况并非如此.这就是我得到的 当试图 go build maps :

build github.com/X/maps: cannot load github/X/go-log-util: cannot find module providing package github/X/go-log-util

这是怎么回事?我一直在努力从 go dep 搬家去模块,但到目前为止运气不好。

相关代码如下。

非常感谢! :)

/maps/main.go

package main

import (
    "fmt"
    "net/http"
    "os"
    "os/signal"
    "syscall"
    "time"

    log "github/X/go-log-util"

    dbUtil "github.com/X/go-database-util"
    "github.com/X/maps/api"
    "github.com/gorilla/mux"
    "github.com/jinzhu/gorm"
    "github.com/namsral/flag"
    "github.com/sirupsen/logrus"
    "github.com/urfave/negroni"
)

type configuration struct {
    Addr       string
    LogLevel   string
    DBSettings dbUtil.Settings
}

var (
    config configuration
    db     *gorm.DB
)

func main() {
    loadConfig()
    flag.Parse()
    logrus.Infof("Using config: %#v", config)
    var err error
    db, err = dbUtil.Setup(config.DBSettings)
    if err != nil {
        logrus.Fatal(err)
    }

    n := negroni.New()
    n.Use(negroni.HandlerFunc(log.LoggingMiddleware))
    router := mux.NewRouter()
    userRoutes := mux.NewRouter()
    userRoutes.HandleFunc("/api/maps/info", api.HandleRead).Methods("GET")
    n.UseHandler(router)
    srv := &http.Server{
        Handler: n,
        Addr:    config.Addr,
    }

    setupCleanupHandler()
    logrus.Fatal(srv.ListenAndServe())
}

func loadConfig() {
    flag.StringVar(&config.Addr, "addr", "localhost:8080", "HTTP service address")
    flag.StringVar(&config.LogLevel, "log-level", "debug",
        "Application logging level (debug, info, warning, error, fatal, panic)")

    var dbPassword string
    var connMaxLifetime int
    flag.StringVar(&config.DBSettings.Host, "db-host", "", "DB host")
    flag.StringVar(&config.DBSettings.User, "maps-db-username", "", "DB user")
    flag.StringVar(&config.DBSettings.DBName, "maps-db-name", "X", "DB name")
    flag.StringVar(&dbPassword, "maps-db-password", "", "DB password")
    flag.IntVar(&config.DBSettings.MaxIdleConns, "db-max-idle-conns", 10, "DB max idle connections")
    flag.IntVar(&config.DBSettings.MaxOpenConns, "db-max-open-conns", 100, "DB max open connections")
    flag.BoolVar(&config.DBSettings.LogEnabled, "db-enable-log", false, "Enable detailed gorm log")
    flag.IntVar(&connMaxLifetime, "db-max-lifetime-conns", 5, "DB max connection lifetime (minutes)")
    config.DBSettings.Password = &dbPassword
    config.DBSettings.ConnMaxLifetime = time.Duration(connMaxLifetime) * time.Minute
}

func healthHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "OK SO")
}

func setupCleanupHandler() {
    sigs := make(chan os.Signal, 2)
    signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)
    go func() {
        <-sigs
        logrus.Info("Server shutdown, cleaning up resources")
        db.Close()
        os.Exit(1)
    }()
}

/maps/go.mod

module github.com/X/maps

go 1.12

require (
    github.com/X/go-database-util v0.0.0
    github.com/X/go-log-util v0.0.0
    github.com/gorilla/mux v1.6.2
    github.com/jinzhu/gorm v1.9.10
    github.com/namsral/flag v1.7.4-pre
    github.com/sirupsen/logrus v1.4.2
    github.com/urfave/negroni v1.0.0
)

replace github.com/X/go-log-util => ../go-log-util

replace github.com/X/go-database-util => ../go-database-util

/go-database-util/db.mod

// Package db provides utility functions to perform database related tasks.
// While most of the code is generic, it assumes to be working using a postgres driver.
package db

import (
    "fmt"
    "time"

    "github.com/jinzhu/gorm"
    // required in order to load postgres driver.
    _ "github.com/jinzhu/gorm/dialects/postgres"
    "github.com/sirupsen/logrus"
)

// Settings store a database main configuration options.
type Settings struct {
    Host     string
    User     string
    DBName   string
    Password *string

    MaxIdleConns    int
    MaxOpenConns    int
    ConnMaxLifetime time.Duration

    LogEnabled bool
}

// Setup configures the settings for database connections.
func Setup(s Settings) (*gorm.DB, error) {
    connURL := fmt.Sprintf("host=%s user=%s dbname=%s sslmode=disable password=%s",
        s.Host, s.User, s.DBName, *s.Password)
    db, err := gorm.Open("postgres", connURL)
    if err != nil {
        return nil, err
    }

    db.DB().SetMaxIdleConns(s.MaxIdleConns)
    db.DB().SetMaxOpenConns(s.MaxOpenConns)

    // broken connections may not be detected; would need a dedicate goroutine
    // setting this to just a few seconds / minutes will solve a lot of issues
    // see https://github.com/go-sql-driver/mysql/issues/529
    db.DB().SetConnMaxLifetime(s.ConnMaxLifetime)
    db.LogMode(s.LogEnabled)
    logger := logrus.New()
    db.SetLogger(logger)
    return db, nil
}

go-database-util/go.mod

module github.com/X/go-database-util

go 1.12

require (
    github.com/jinzhu/gorm v1.9.10
    github.com/sirupsen/logrus v1.4.2
)

go-log-util/log.go

package log

import (
    "context"
    "net/http"
    "os"

    "github.com/sirupsen/logrus"
)

const (
    // RequestIDHeader is the header name for the request id.
    RequestIDHeader = "X-Request-Id"
    // UserIDKey is the key for the user id inside the logger fields.
    UserIDKey = "UserID"
)

// RequestContext returns a new context with the argument context fields
// and a request id.
func RequestContext(ctx context.Context, req *http.Request) context.Context {
    requestID := req.Header.Get(RequestIDHeader)
    reqContext := context.WithValue(ctx, RequestIDHeader, requestID)
    return reqContext
}

// L returns logrus entry with context information.
func L(ctx context.Context) *logrus.Entry {
    logger := logrus.New()
    Configure(logger)

    l := logrus.Fields{
        RequestIDHeader: RequestID(ctx),
    }

    if id := UserID(ctx); id != 0 {
        l[UserIDKey] = id
    }

    return logger.WithFields(l)
}

// RequestID returns the request id from the context.
func RequestID(ctx context.Context) string {
    if id, ok := ctx.Value(RequestIDHeader).(string); ok {
        return id
    }
    return ""
}

// UserID returns the user id from the context.
func UserID(ctx context.Context) uint64 {
    if id, ok := ctx.Value(UserIDKey).(uint64); ok {
        return id
    }
    return 0
}

// Setup initializes and sets configuration options for the logger.
func Setup(logLevel string, logger *logrus.Logger) {

    logger.Formatter = &logrus.TextFormatter{
        FullTimestamp: true,
    }

    logger.Out = os.Stdout
    level, _ := logrus.ParseLevel(logLevel)
    logger.Level = level
}

// Configure initializes and set configuration options for the logger.
func Configure(logger *logrus.Logger) {

    logger.Formatter = &logrus.TextFormatter{
        FullTimestamp: true,
    }

    logger.Out = os.Stdout
    logger.Level = logrus.StandardLogger().Level
}

// LoggingMiddleware creates a middleware that logs useful information from an
// *http.Request
func LoggingMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
    ctx := RequestContext(r.Context(), r)
    logFields := logrus.Fields{
        "remoteAddr":      r.RemoteAddr,
        "method":          r.Method,
        "url":             r.URL,
        "x-forwarded-for": r.Header.Get("X-Forwarded-For"),
    }

    L(ctx).WithFields(logFields).Info("Incoming request")
    next(w, r.WithContext(ctx))
}

go-log-util/go.mod

module github.com/X/go-log-util

go 1.12

require github.com/sirupsen/logrus v1.4.2

最佳答案

我真傻,/maps/main.go 的导入路径中有一个拼写错误:"github/X/go-log-util"。 .com 不见了! :)

关于go - 尝试使用本地子模块时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57185912/

有关go - 尝试使用本地子模块时出现问题的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  5. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  6. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  7. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  8. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  9. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  10. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

随机推荐