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 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。