草庐IT

go - 从go程序中的其他文件访问对象

coder 2024-07-06 原文

Goji 微框架 has a fully functional example app with three files , main.go, models.go 和 middleware.go。我使用 go get 命令安装了框架

go get github.com/zenazn/goji

因此在我的 GOPATH 中有这样的示例应用程序

src/github.com/zenazn/goji/example

如果我导航到/example/并运行 go run main.go,它会给我一个错误,表明 main.go 文件没有从 中间件访问对象.gomodels.go 文件,像这样

./main.go:39: undefined: PlainText
./main.go:47: undefined: SuperSecure
./main.go:73: undefined: Greets
./main.go:74: undefined: Greets
./main.go:85: undefined: Greet
./main.go:98: undefined: Greets
./main.go:99: undefined: Greets
./main.go:107: undefined: Users
./main.go:116: undefined: Greets
./main.go:116: too many errors

main.go 中没有导入middleware.gomodels.go 的代码,只有库的常规导入语句。

这些文件应该如何绑定(bind)在一起,以便一个文件中的对象在另一个文件中可用?

来自 main.go

package main

import (
    "fmt"
    "io"
    "net/http"
    "regexp"
    "strconv"

    "github.com/zenazn/goji"
    "github.com/zenazn/goji/param"
    "github.com/zenazn/goji/web"
)

// Note: the code below cuts a lot of corners to make the example app simple.

func main() {
    // Add routes to the global handler
    goji.Get("/", Root)
    // Fully backwards compatible with net/http's Handlers
    goji.Get("/greets", http.RedirectHandler("/", 301))
    // Use your favorite HTTP verbs
    goji.Post("/greets", NewGreet)
    // Use Sinatra-style patterns in your URLs
    goji.Get("/users/:name", GetUser)
    // Goji also supports regular expressions with named capture groups.
    goji.Get(regexp.MustCompile(`^/greets/(?P<id>\d+)$`), GetGreet)

    // Middleware can be used to inject behavior into your app. The
    // middleware for this application are defined in middleware.go, but you
    // can put them wherever you like.
    goji.Use(PlainText)

    admin := web.New()
    goji.Handle("/admin/*", admin)
    admin.Use(SuperSecure)

    // Goji's routing, like Sinatra's, is exact: no effort is made to
    // normalize trailing slashes.
    goji.Get("/admin", http.RedirectHandler("/admin/", 301))


    admin.Get("/admin/", AdminRoot)
    admin.Get("/admin/finances", AdminFinances)

    // Use a custom 404 handler
    goji.NotFound(NotFound)

    goji.Serve()
}

middleware.go

package main

import (
    "encoding/base64"
    "net/http"
    "strings"

    "github.com/zenazn/goji/web"
)

// PlainText sets the content-type of responses to text/plain.
func PlainText(h http.Handler) http.Handler {
    fn := func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "text/plain")
        h.ServeHTTP(w, r)
    }
    return http.HandlerFunc(fn)
}

// Nobody will ever guess this!
const Password = "admin:admin"

// SuperSecure is HTTP Basic Auth middleware for super-secret admin page. Shhhh!
func SuperSecure(c *web.C, h http.Handler) http.Handler {
    fn := func(w http.ResponseWriter, r *http.Request) {
        auth := r.Header.Get("Authorization")
        if !strings.HasPrefix(auth, "Basic ") {
            pleaseAuth(w)
            return
        }

        password, err := base64.StdEncoding.DecodeString(auth[6:])
        if err != nil || string(password) != Password {
            pleaseAuth(w)
            return
        }

        h.ServeHTTP(w, r)
    }
    return http.HandlerFunc(fn)
}

func pleaseAuth(w http.ResponseWriter) {
    w.Header().Set("WWW-Authenticate", `Basic realm="Gritter"`)
    w.WriteHeader(http.StatusUnauthorized)
    w.Write([]byte("Go away!\n"))
}

models.go

package main

import (
    "fmt"
    "io"
    "time"
)

// A Greet is a 140-character micro-blogpost that has no resemblance whatsoever
// to the noise a bird makes.
type Greet struct {
    User    string    `param:"user"`
    Message string    `param:"message"`
    Time    time.Time `param:"time"`
}

// Store all our greets in a big list in memory, because, let's be honest, who's
// actually going to use a service that only allows you to post 140-character
// messages?
var Greets = []Greet{
    {"carl", "Welcome to Gritter!", time.Now()},
    {"alice", "Wanna know a secret?", time.Now()},
    {"bob", "Okay!", time.Now()},
    {"eve", "I'm listening...", time.Now()},
}

// Write out a representation of the greet
func (g Greet) Write(w io.Writer) {
    fmt.Fprintf(w, "%s\n@%s at %s\n---\n", g.Message, g.User,
        g.Time.Format(time.UnixDate))
}

// A User is a person. It may even be someone you know. Or a rabbit. Hard to say
// from here.
type User struct {
    Name, Bio string
}

// All the users we know about! There aren't very many...
var Users = map[string]User{
    "alice": {"Alice in Wonderland", "Eating mushrooms"},
    "bob":   {"Bob the Builder", "Making children dumber"},
    "carl":  {"Carl Jackson", "Duct tape aficionado"},
}

// Write out the user
func (u User) Write(w io.Writer, handle string) {
    fmt.Fprintf(w, "%s (@%s)\n%s\n", u.Name, handle, u.Bio)
}

最佳答案

只需使用 go rungo run *.go 你只运行/编译 main.go 其他文件不包括在内。

关于go - 从go程序中的其他文件访问对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24640352/

有关go - 从go程序中的其他文件访问对象的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  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 - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  5. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  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 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

    我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

  8. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  9. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  10. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

随机推荐