gin框架入门 | 青训营笔记

109 阅读1分钟

这是我参与「第三届青训营 -后端场」笔记创作活动的的第3篇笔记

不采用框架启动服务器

package main

import (
   "fmt"
   "net/http"
)

func sayHello(w http.ResponseWriter,r *http.Request){
   _, _ = fmt.Fprint(w, "hello world")
}

func main() {
   http.HandleFunc("/hello", sayHello)
   err := http.ListenAndServe(":9090", nil)
   if err != nil {
      fmt.Printf("http server failed, err: %v\n", err)
      return
   }
}

gin 框架启动服务器

package main

import "github.com/gin-gonic/gin"

func main() {
   // 返回默认的路由引擎
   router := gin.Default()
   // Get请求访问hello时,放回第二个方法中的值
   router.GET("/hello", func(context *gin.Context) {
      context.JSON(200, gin.H{
         "msg": "Hello go",
      })
   })
   // 启动服务绑定端口
   router.Run(":9090")
}