Created
March 31, 2015 18:57
-
-
Save anonymous/e168fc8fe9be985901fd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"net/http" | |
"strconv" | |
"github.com/labstack/echo" | |
mw "github.com/labstack/echo/middleware" | |
"github.com/rs/cors" | |
"github.com/thoas/stats" | |
) | |
type user struct { | |
ID string `json:"id"` | |
Name string `json:"name"` | |
} | |
var users map[string]user | |
var nextid int | |
func init() { | |
users = map[string]user{ | |
"1": user{ | |
ID: "1", | |
Name: "Wreck-It Ralph", | |
}, | |
} | |
nextid = 2 | |
} | |
func nextUserId() string { | |
var next = nextid; | |
nextid += 1; | |
return strconv.Itoa(next) | |
} | |
func createUser(c *echo.Context) { | |
u := new(user) | |
u.ID = nextUserId() | |
u.Name = c.Param("name") | |
if c.Bind(u) { | |
users[u.ID] = *u | |
c.JSON(http.StatusCreated, u) | |
} | |
} | |
func getUsers(c *echo.Context) { | |
c.JSON(http.StatusOK, users) | |
} | |
func getUser(c *echo.Context) { | |
c.JSON(http.StatusOK, users[c.P(0)]) | |
} | |
func main() { | |
e := echo.New() | |
//*************************// | |
// Built-in middleware // | |
//*************************// | |
e.Use(mw.Logger) | |
//****************************// | |
// Third-party middleware // | |
//****************************// | |
// https://github.com/rs/cors | |
e.Use(cors.Default().Handler) | |
// https://github.com/thoas/stats | |
s := stats.New() | |
e.Use(s.Handler) | |
// Route | |
e.Get("/stats", func(c *echo.Context) { | |
c.JSON(200, s.Data()) | |
}) | |
// Serve index file | |
e.Index("public/index.html") | |
// Serve static files | |
// e.Static("/js", "public/js") | |
//************// | |
// Routes // | |
//************// | |
e.Get("/users", getUsers) | |
e.Get("/users/:id", getUser) | |
e.Post("/users", createUser) | |
e.Post("/users/:name", createUser) | |
// Start server | |
e.Run("localhost:8080") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment