Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang API with echo framework

Tags:

json

go

api

go-echo

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?

like image 616
gempir Avatar asked Dec 15 '22 07:12

gempir


1 Answers

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.

like image 81
Christian Witts Avatar answered Dec 17 '22 00:12

Christian Witts