https://github.com/gin-gonic/gin

  1. package main
  2. import "github.com/gin-gonic/gin"
  3. func main() {
  4. r := gin.Default()
  5. r.GET("/ping", func(c *gin.Context) {
  6. c.JSON(200, gin.H{
  7. "message": "pong",
  8. })
  9. })
  10. r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
  11. }

run

  1. # run example.go and visit 0.0.0.0:8080/ping (for windows "localhost:8080/ping") on browser
  2. $ go run example.go

examples

https://github.com/gin-gonic/examples

restful

  1. func main() {
  2. // Creates a gin router with default middleware:
  3. // logger and recovery (crash-free) middleware
  4. router := gin.Default()
  5. // r := gin.New()
  6. // r.Use(gin.Logger())
  7. // 静态文件
  8. router.Static("/assets", "./assets")
  9. router.StaticFS("/more_static", http.Dir("my_file_system"))
  10. router.StaticFile("/favicon.ico", "./resources/favicon.ico")
  11. router.GET("/someGet", getting)
  12. router.POST("/somePost", posting)
  13. router.PUT("/somePut", putting)
  14. router.DELETE("/someDelete", deleting)
  15. router.PATCH("/somePatch", patching)
  16. router.HEAD("/someHead", head)
  17. router.OPTIONS("/someOptions", options)
  18. // params
  19. router.GET("/user/:name", func(c *gin.Context) {
  20. name := c.Param("name")
  21. c.String(http.StatusOK, "Hello %s", name)
  22. })
  23. // query
  24. router.GET("/welcome", func(c *gin.Context) {
  25. firstname := c.DefaultQuery("firstname", "Guest")
  26. lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")
  27. c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
  28. })
  29. // post
  30. router.POST("/post", func(c *gin.Context) {
  31. id := c.Query("id")
  32. page := c.DefaultQuery("page", "0")
  33. name := c.PostForm("name")
  34. message := c.PostForm("message")
  35. fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
  36. })
  37. // json
  38. r.GET("/someJSON", func(c *gin.Context) {
  39. c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
  40. })
  41. // 重定向
  42. r.GET("/test", func(c *gin.Context) {
  43. c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")
  44. })
  45. // By default it serves on :8080 unless a
  46. // PORT environment variable was defined.
  47. router.Run()
  48. // router.Run(":3000") for a hard coded port
  49. }

build

  1. go build main.go
  2. // 上面的命令将构建一个可执行的二进制文件 main ,你可以使用 $ ./main 命令来运行构建号的应用。 哇,我们的 todo 应用现在运行在了本地的 8080 端口了。 它将在终端显示调试日志,因为 gin 默认以 debug 模式运行在 8080 端口。

todo-mvc

https://medium.com/@_ektagarg/golang-a-todo-app-using-gin-980ebb7853c8

to view code

https://github1s.com/ektagarg/gin-gorm-todo-app