doutuoben6908 2017-11-14 02:41
浏览 51
已采纳

未定义:含Mux的应用

So I just started learning Go yesterday and I have been following a fairly simple tutorial on creating a restful api. I can run the tests and everything but when I try to run the app and have it listen on a part it gives me undefined: App.

I cannot seem to find the error in this as Initialize and run should be sufficient enough to start the server. The tutorial also has it exactly like this and I followed it carefully.

UPDATE:

As clarification I attempt to run the program with go run main.go and that's what prompts the error.

I also attempted to follow the advice of an answer and ran go run main.go app.go and I get undefined: getUsers and it points to the line where it says users, err := getUsers(a.DB, start, count). I have added them to my app.go code below.

main.go

package main

func main() {
    a := App{}

    a.Initialize("root", "password", "user")

    a.Run(":8080")
}

app.go

package main

import (
    "fmt"
    "log"
    "strconv"
    "encoding/json"
    "net/http"
    "github.com/gorilla/mux"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)

type App struct {
    Router *mux.Router
    DB     *sql.DB
}

func (a *App) Initialize(user, password, dbname string) {
    connectionString := fmt.Sprintf("%s:%s@/%s", user, password, dbname)

    var err error

    a.DB, err = sql.Open("mysql", connectionString)

    if err != nil {
        log.Fatal(err)
    }

    a.Router = mux.NewRouter()
    a.initializeRoutes()
}

func (a *App) initializeRoutes() {
    a.Router.HandleFunc("/users", a.getUsers).Methods("GET")
}

func (a *App) Run(addr string) {
    log.Fatal(http.ListenAndServe(addr, a.Router))
}

func (a *App) getUsers(w http.ResponseWriter, r *http.Request) {
    count, _ := strconv.Atoi(r.FormValue("count"))
    start, _ := strconv.Atoi(r.FormValue("start"))

    if count > 10 || count < 1 {
        count = 10
    }

    if start < 0 {
        start = 0
    }

    users, err := getUsers(a.DB, start, count)

    if err != nil {
        respondWithError(w, http.StatusInternalServerError, err.Error())

        return
    }

    respondWithJSON(w, http.StatusOK, users);
}
  • 写回答

3条回答 默认 最新

  • douchixu3686 2017-11-14 02:49
    关注

    How do you run it? If with go run try to pass it all the files:

    go run main.go app.go
    

    Or even with asterisk to catch them all:

    go run *.go
    

    Another option: build application then run it:

    go build -o app && ./app
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错