Advertisement
Guest User

Untitled

a guest
Dec 8th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "github.com/labstack/echo"
  7. "github.com/labstack/gommon/log"
  8. "io/ioutil"
  9. "net/http"
  10. )
  11.  
  12. type Dev struct {
  13. Name string `json:"name"`
  14. Type string `json:"type"`
  15. }
  16.  
  17. func helloWorld(c echo.Context) error {
  18. return c.String(http.StatusOK, "Hello World")
  19. }
  20.  
  21. func getDev(c echo.Context) error {
  22. devName := c.QueryParam("name")
  23. devType := c.QueryParam("type")
  24.  
  25. dataType := c.Param("data")
  26.  
  27. if dataType == "string" {
  28.  
  29. return c.String(http.StatusOK, fmt.Sprintf("Dev name is: %s and type: %s\n", devName, devType))
  30. }
  31.  
  32. if dataType == "json" {
  33. return c.JSON(http.StatusOK, map[string]string{
  34. "name": devName,
  35. "type": devType,
  36. })
  37. }
  38. return c.JSON(http.StatusBadRequest, map[string]string{
  39. "error": "You need to lets us know if you want json or string",
  40. })
  41. }
  42.  
  43. func addDev(c echo.Context) error {
  44. dev := Dev{}
  45. defer c.Request().Body.Close()
  46.  
  47. b, err := ioutil.ReadAll(c.Request().Body)
  48. if err != nil {
  49. log.Printf("Failed reading the request body %s", err)
  50. return c.String(http.StatusInternalServerError, "")
  51. }
  52.  
  53. err = json.Unmarshal(b, &dev)
  54. if err != nil {
  55. log.Printf("Failed unmarshaling in addDev %s", err)
  56. return c.String(http.StatusInternalServerError, fmt.Sprintf("Error: %s", err))
  57. }
  58.  
  59. log.Printf("This is your dev: %v", dev)
  60. return c.String(http.StatusOK, "We got your dev")
  61. }
  62.  
  63. func main() {
  64. e := echo.New()
  65. e.GET("/", helloWorld)
  66. e.GET("/devs/:data", getDev)
  67. e.POST("/devs", addDev)
  68. e.Logger.Fatal(e.Start(":8080"))
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement