Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "encoding/json"
- "fmt"
- "github.com/labstack/echo"
- "github.com/labstack/gommon/log"
- "io/ioutil"
- "net/http"
- )
- type Dev struct {
- Name string `json:"name"`
- Type string `json:"type"`
- }
- func helloWorld(c echo.Context) error {
- return c.String(http.StatusOK, "Hello World")
- }
- func getDev(c echo.Context) error {
- devName := c.QueryParam("name")
- devType := c.QueryParam("type")
- dataType := c.Param("data")
- if dataType == "string" {
- return c.String(http.StatusOK, fmt.Sprintf("Dev name is: %s and type: %s\n", devName, devType))
- }
- if dataType == "json" {
- return c.JSON(http.StatusOK, map[string]string{
- "name": devName,
- "type": devType,
- })
- }
- return c.JSON(http.StatusBadRequest, map[string]string{
- "error": "You need to lets us know if you want json or string",
- })
- }
- func addDev(c echo.Context) error {
- dev := Dev{}
- defer c.Request().Body.Close()
- b, err := ioutil.ReadAll(c.Request().Body)
- if err != nil {
- log.Printf("Failed reading the request body %s", err)
- return c.String(http.StatusInternalServerError, "")
- }
- err = json.Unmarshal(b, &dev)
- if err != nil {
- log.Printf("Failed unmarshaling in addDev %s", err)
- return c.String(http.StatusInternalServerError, fmt.Sprintf("Error: %s", err))
- }
- log.Printf("This is your dev: %v", dev)
- return c.String(http.StatusOK, "We got your dev")
- }
- func main() {
- e := echo.New()
- e.GET("/", helloWorld)
- e.GET("/devs/:data", getDev)
- e.POST("/devs", addDev)
- e.Logger.Fatal(e.Start(":8080"))
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement