2014-07-08 94 views
0

Go的goji微框架has a fully functional example app with three files,main.go, models.go and middleware.go。我使用Go get命令在go程序中访问其他文件中的对象

go get github.com/zenazn/goji 

,并因此具有示例应用availabl在我GOPATH这样

src/github.com/zenazn/goji/example 

如果我浏览到/例子/和运行go run main.go安装框架,它给我的错误这表明main.go文件不会从middleware.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,只是库的常规导入语句。

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

从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("https://stackoverflow.com/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\[email protected]%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) 
} 

回答

2

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

+0

谢谢,但请澄清一些事情。如何使用这个项目'https:// github.com/mantishK/gonotevanilla',例如,你只运行'main.go'文件来运行它。自述文件显示'go run github.com/mantishK/gonotevanilla/main.go'这个项目中有很多其他文件,为什么只有该项目中的'main.go'文件需要运行,但是,就像你在你的回答中说,这个项目中的每个文件(即OP中链接的项目)都需要编译。你能解释一下这个区别吗? – BrainLikeADullPencil

+0

,因为main.go正在导入“github.com/mantishK/gonotevanilla/controllers”作为库。如果你进入这些文件,你会发现这个软件包不是'主',而是另一个 – fabrizioM

0

您应该最好使用go build - 构建一个二进制文件,然后您可以运行为./example

Go在包而不是文件上运行,而go run最终只是测试示例或简单程序时使用的方便(它构建二进制文件并有效地丢弃它)。

相关问题