使用Echo框架的Golang API

huangapple go评论85阅读模式
英文:

golang API with echo framework

问题

我正在使用一个名为echo的轻量级Web框架(https://github.com/labstack/echo),并尝试用它构建一个非常简单的API。

这是我的其中一个路由:

e.Get("/v1/:channel/:username", getData)

这是getData函数,它从MySQL数据库中进行一个非常简单的SELECT操作:

func getData(c echo.Context) error {
  quote := new(Quote)  
  for rows.Next() {
    var username string
    var message string
    err = rows.Scan(&username, &message)
    checkErr(err)
    quote.username = username
    quote.message = message
  }
  log.Println(quote)

  defer rows.Close()
  return c.JSON(http.StatusOK, quote)
}

我还有一个用于返回值的基本结构体:

type Quote struct {
  username string
  message  string
}

不幸的是,我无法弄清楚如何返回JSON。当我尝试这段代码时,服务器的响应总是{}。我尝试了返回c.String,它可以正常工作并输出响应,但我想返回JSON。

我按照这个示例进行操作,但实在看不出问题在哪里。https://github.com/labstack/echox/blob/master/recipe/crud/main.go

你有什么想法,我做错了什么吗?

英文:

I'm using a light framework web framework named echo (https://github.com/labstack/echo) and I am trying to build a very simple API with it.

this is one of my routes

 e.Get("/v1/:channel/:username", getData)

this is the getData function it does a very simple SELECT from a mysql database

func getData(c echo.Context) error {
  quote := new(Quote)  
  for rows.Next() {
    	var username string
    	var message string
    	err = rows.Scan(&username, &message)
    	checkErr(err)
    	quote.username = username
    	quote.message = message
  }
  log.Println(quote)

  defer rows.Close()
  return c.JSON(http.StatusOK, quote)
}

I also have this basic struct for the return value

type Quote struct {
	username string
	message  string
}

Sadly I can't figure out how to return a JSON now.
When I try this code the response from the server is always just {}
I tried return c.String which works fine and outputs a response but I would like to return a JSON.

I followed this example and can't really see the problem here.
https://github.com/labstack/echox/blob/master/recipe/crud/main.go

Any idea what I am doing wrong?

答案1

得分: 15

你的结构体没有可导出的值,因为名称是小写的。

type Quote struct {
    Username string `json:"username"`
    Password string `json:"password"`
}

你还可以在代码片段中注释编组键的名称,这样如果你想从内部表示更改名称为外部表示,就可以了。

英文:

Your struct doesn't have exportable values, as the names are lowercase.

type Quote struct {
    Username string `json:"username"`
    Password string `json:"password"`
}

You can also annotate the name of the marshalled key as I've posted in the code snippet, so if you want to change the name from an internal to external representation you can.

huangapple
  • 本文由 发表于 2016年4月8日 20:39:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/36499798.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定