下面是我使用 Labstack 的 Echo 用 Go 编写的 Web 应用程序的入口点:
package main
import (
"github.com/labstack/echo"
mw "github.com/labstack/echo/middleware"
)
func main() {
controller := controllers.NewUserController(getSession())
app := echo.New()
app.Use(mw.Logger())
app.Use(mw.Recover())
app.SetDebug(true)
app.Post("/users", controller.CreateUser)
app.Get("/users", controller.ListUsers)
app.Get("/users/:id", controller.GetUser)
app.Patch("/users/:id", controller.UpdateUser)
app.Delete("/users/:id", controller.DeleteUser)
app.Run(":8000")
}
Run Code Online (Sandbox Code Playgroud)
如何重用在Echo
应用程序中实例化的日志中间件?我试过这个:
包控制器
import (
"net/http"
"github.com/labstack/echo"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type (
UserController struct {
session *mgo.Session
}
)
func NewUserController(s *mgo.Session) *UserController {
return &UserController{s}
}
func (userController UserController) CreateUser(context *echo.Context) error {
user := &models.User{}
if …
Run Code Online (Sandbox Code Playgroud) 我正在使用 swaggo ( https://github.com/swaggo/swag ) 为我的 API 自动创建一个有效的 swagger 规范。
swagger 规范允许我运行所有 API 端点并接收响应。
然后,我将 JWT 身份验证添加到我的所有端点。现在我无法使用 swagger 规范来运行任何端点,因为它总是无法通过身份验证。
我需要向每个端点添加哪些注释,以配置 Swagger 规范以允许传递 JWT?
我已阅读https://github.com/swaggo/swag上的自述文件并进行谷歌搜索,但无济于事。
我正在使用Echo在Golang中构建一个极简服务器。
在其中,Echo可以在内部将传入的JSON请求有效负载绑定到结构并访问有效负载。
但是我有一个场景,我只知道传入的JSON请求有效负载的3个字段,并且在这种情况下绑定不起作用。
我仍如何访问我关心的3个字段?如果我无法在Echo中做到这一点,您能推荐我一个与Echo的上下文结构兼容的JSON解码器吗?
我对 Go 有点陌生,所以,如果这是一个愚蠢的问题,我很抱歉。
我最近一直在尝试使用 Echo 的一些 API。我正在尝试测试 Go echo 的路由(POST)处理程序,它获取 json 并将其放入数组中。下面是处理程序main.go和测试test_main.go的代码
main.go
type Houses struct {
Name string `json:"name,ommitempty"`
Address string `json:"address,omitempty"`
}
var houses []Houses
func newHouse(c echo.Context) error {
m := echo.Map{}
if err := c.Bind(&m); err != nil {
return err
}
dv := Houses{
Name: m["name"].(string),
Address: m["address"].(string),
}
houses = append(houses, dv)
js, _ := json.Marshal(houses)
fmt.Println(fmt.Sprintf("%s", js))
return c.JSON(http.StatusOK, string(js))
}
Run Code Online (Sandbox Code Playgroud)
test_main.go
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/labstack/echo" …
Run Code Online (Sandbox Code Playgroud) 我正在设置一个Web服务器,Go(使用Echo)作为后端,Angular 6作为前端.我做的是使用Angular-cli'ng new my-app'创建一个简单的应用程序,添加一个helloworld组件和一个'/ helloworld'路径,然后使用'ng build --prod'将其构建到生产中,输出为'dist '文件夹.文件夹结构:
dist
??? assets
? ??? icons
? ??? logo.png
??? favicon.ico
??? index.html
??? main.js
??? polyfills.js
??? runtime.js
??? styles.css
Run Code Online (Sandbox Code Playgroud)
然后,我使用以下代码main.go为'dist'文件夹中的静态文件提供服务
func main() {
e := echo.New()
e.Static("/", "dist")
e.File("/", "dist/index.html")
e.Start(":3000")
}
Run Code Online (Sandbox Code Playgroud)
现在,当我使用浏览器并转到'localhost:3000 /'时,页面将正确提供,我可以使用href导航,感谢Angular路由,例如:'localhost:3000/home'页面将正确显示但如果我尝试刷新它,那么Echo将返回一个页面内容,显示:
{"未找到信息"}
我知道我可以手动设置路线,如下所示:
e.File("/home","dist/index.html")
Run Code Online (Sandbox Code Playgroud)
但是,如果我有更多的路线,那么完成所有这些操作是相当麻烦的.
我需要的是,没有为Echo定义的任何路由都将映射到'index.html'.我确实尝试过:
e.File("/*", "dist/index.html")
Run Code Online (Sandbox Code Playgroud)
和
e.GET("/*", func(c echo.Context)
return c.File("dist/index.html")
})
Run Code Online (Sandbox Code Playgroud)
但后来我得到一个有错误的空白页面
"Uncaught SyntaxError: Unexpected token < "
Run Code Online (Sandbox Code Playgroud)
所有3个文件main.js,polyfill.js和runtime.js
我是Echo的新手,所以我不知道该怎么做.
我想将“电报机器人”与“回声框架”一起使用(当服务器启动时,回声和电报机器人一起工作)。我使用了下面的代码,但是当我运行它时,电报机器人没有启动。
我的 main.go:
package main
import (
"database/sql"
"log"
"net/http"
"strings"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/labstack/echo"
_ "github.com/mattn/go-sqlite3"
)
func main() {
e := echo.New()
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})
_ = e.Start(":1323")
db, err := sql.Open("sqlite3", "./criticism.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
bot, err := tgbotapi.NewBotAPI("")
if err != nil {
log.Fatal(err)
}
bot.Debug = true
log.Printf("Authorized on account %s", bot.Self.UserName)
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates, err := bot.GetUpdatesChan(u)
for …
Run Code Online (Sandbox Code Playgroud) 我正在使用 labstack 的Echo 框架在 Golang 中构建 API。现在,当我想测试端点时,我遇到了一个似乎无法解决的问题。
我有一个像这样的处理函数
func DoStuff(c echo.Context) error {
businessUnit := strings.ToUpper(c.FormValue("bu"))
week := c.FormValue("wk")
file, _ := c.FormFile("file")
...
}
Run Code Online (Sandbox Code Playgroud)
处理程序工作得很好。我现在遇到的问题是为此编写集成测试。
该端点接受一个Content-Type: multipart/form-data
.
这是我的一些其他处理程序测试的样子:
func TestDoStuff(t *testing.T) {
// Not sure about this part tho
body := new(bytes.Buffer)
writer := multipart.NewWriter(body)
writer.WriteField("bu", "HFL")
writer.WriteField("wk", "10")
part, _ := writer.CreateFormFile("file", "file.csv")
part.Write([]byte(`sample`))
e := echo.New()
req := httptest.NewRequest(http.MethodPost, "/endpoint", body)
req.Header.Add("Content-Type", "multipart/form-data")
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
if assert.NotPanics(t, func(){ …
Run Code Online (Sandbox Code Playgroud) 我在使用Go 的官方 MongoDB 驱动程序为某些数据创建唯一索引时遇到一些问题。
所以我有一个这样的结构:
type Product struct {
ID primitive.ObjectID `json:"_id" bson:"_id"`
Name string `json:"name" bson:"name"`
Price float64 `json:"price" bson:"price"`
Attribute []Attribute `json:"attribute" bson:"attribute"`
Category string `json:"category" bson:"category"`
}
Run Code Online (Sandbox Code Playgroud)
然后我想为该name
属性创建一个唯一索引。我尝试在我的函数中做类似的事情Create
(对于产品)
func Create(c echo.Context) error {
//unique index here
indexModel, err := productCollection.Indexes().CreateOne(context.Background(),
IndexModel{
Keys: bsonx.Doc{{"name", bsonx.Int32(1)}},
Options: options.Index().SetUnique(true),
})
if err != nil {
log.Fatalf("something went wrong: %+v", err)
}
//create the product here
p := new(Product)
if err := c.Bind(p); err != nil …
Run Code Online (Sandbox Code Playgroud) 但是我在 Echo 框架中使用 websocket 而不是 Gorilla。所以我认为方法会有所不同。
Echo 确实提供了示例。但它只显示了如何与单个客户端连接。当有多个客户端时,其他客户端不会收到来自服务器的消息。
如何让服务器向所有连接的客户端广播消息?
来自引用链接的接受答案说我必须使用连接池向所有连接广播消息。我怎样才能在 Echo 框架中做到这一点?
我正在使用 PostgreSQL 和 golang 编写后端。我在获取工资栏总和时遇到问题。
这是我的代码:
func GetSalarySum(c echo.Context) error {
db, err := gorm.Open("postgres", "host=localhost port=5433 user=postgres dbname=testone password=root sslmode=disable")
checkError(err)
defer db.Close()
type UpdatedAddress struct {
City string `json:"city;"`
State string `json:"state;"`
Pin string `json:"pin;"`
}
type UpdatedContact struct {
ID uint `json:"id;"`
Mobile string `json:"mobile;"`
Email string `json:"email;"`
}
type NewPerson struct {
ID int `gorm:"primary_key:true;"`
Firstname string `json:"firstname;"`
Lastname string `json:"lastname;"`
Gender string `json:"gender;"`
Salary uint `json:salary;`
Age uint `json:"age"`
Address UpdatedAddress `json:"address"`
Contact UpdatedContact `json:"contact"` …
Run Code Online (Sandbox Code Playgroud) go ×10
go-echo ×10
angular ×1
go-gorm ×1
indexing ×1
json ×1
mongodb ×1
post ×1
postgresql ×1
swagger ×1
swagger-2.0 ×1
telegram-bot ×1
websocket ×1