开启一个简单的API服务。
golang的教程网上一大堆,官网也有非常详细的教程,这里不在赘述这些基础语法教程,我们意在快速进入项目开发阶段。 golang好用语法教程传送门: m.runoob.com/go/
编写第一个API
- 下载gin框架,一个非常好用的写API的框架,使用也很广泛
go mod get github.com/gin-gonic/gin
- 创建API文件夹:apis
- 在apis创建第一个API文档:hello.go
- 导入gin
import "github.com/gin-gonic/gin"
- 实现一个入参为name,返回为:hello name的api
package apis
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)
// API入参参数
type HttpRequest struct {
Name string `json:"name"`
}
// API响应参数
type HttpRespone struct {
Status int `json:"status"`
Message string `json:"message"`
Data string `json:"data"`
}
/*
实现一个入参为name,响应为:hello name的api
这个例子中,异常信息通过status和message返回,api响应状态正常,如果需要响应400等异常状态,可以更换c.JSON(http.StatusOK, res)中的StatusOK
*/
func Hello(c *gin.Context) {
// 声明req
var req HttpRequest
// 声明res并初始化
var res = HttpRespone{}
// 获取api请求参数
err := c.ShouldBindBodyWith(&req, binding.JSON)
// 出现错误,则响应错误信息
if err != nil {
res.Status = 10
res.Message = "读取请求参数错误"
c.JSON(http.StatusOK, res)
return
}
// 判断是否入参name
if req.Name == "" {
res.Status = 20
res.Message = "参数name为空"
c.JSON(http.StatusOK, res)
return
}
// 正常响应 hello name
res.Status = 0
res.Message = "成功"
res.Data = fmt.Sprintf("hello %v", req.Name)
c.JSON(http.StatusOK, res)
}
- 在apis文件夹中创建apis.go,编写api路由注册和服务启动方法
package apis
import (
"net/http"
"github.com/gin-gonic/gin"
)
func StartHttp() {
// 设置为发布模式(初始化路由之前设置)
gin.SetMode(gin.ReleaseMode)
// gin 默认中间件
r := gin.Default()
// 访问一个错误路由时,返回404
r.NoRoute(func(c *gin.Context) {
c.JSON(http.StatusNotFound, gin.H{
"status": 404,
"message": "404, page not exists!",
})
})
// 注册hello路由
r.POST("/hello", Hello)
// 启动API服务
if err := r.Run(":8080"); err != nil {
panic(err)
}
}
- 入口文件main.go引用apis模块
package main
import "prj_aiee/apis"
func main() {
apis.StartHttp()
}
- 以上就是我们一个完整的API服务,虽然功能简单。 启动服务
go run main.go
- 调用api
curl -X POST "http://localhost:8080/hello" -H "content-type: application/json" -d "{\"name\": \"aiee\"}"
响应如下: {"status":0,"message":"成功","data":"hello aiee"}
项目代码: github.com/liyonge-cm/…