基于gin一个还算比较优雅的controller实现
看了两天时间的go,对于go的编码风格还不是很了解,但是了解到go并未有Java那样成体系的编码风格规范,所以自己浅尝试了一下,风格无对错,欢迎交流讨论~
controller层:
package api
import (
"errors"
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
import "awesomeProject/src/server"
type pathAndHandler struct {
path string
handler gin.HandlerFunc
httpMethod string
}
func getApis() []pathAndHandler {
return []pathAndHandler{
{"/", sayHello, http.MethodGet},
{"/label/v1", sentenceToWord, http.MethodPost},
{"/label/v2", textToSentence, http.MethodPost},
}
}
func instances() *gin.Engine {
return server.Init()
}
func Register() (server.Server, error) {
server := instances()
for _, api := range getApis() {
switch api.httpMethod {
case http.MethodGet:
server.GET(api.path, api.handler)
case http.MethodPost:
server.POST(api.path, api.handler)
case http.MethodDelete:
server.DELETE(api.path, api.handler)
case http.MethodHead:
server.HEAD(api.path, api.handler)
case http.MethodPut:
server.PUT(api.path, api.handler)
case http.MethodOptions:
server.OPTIONS(api.path, api.handler)
case http.MethodPatch:
server.PATCH(api.path, api.handler)
default:
fmt.Println("请求方法不支持")
return nil, errors.New("unsupported method")
}
}
return server, nil
}
func sentenceToWord(context *gin.Context) {
//todo 业务逻辑
}
func textToSentence(context *gin.Context) {
}
func sayHello(ctx *gin.Context) {
ctx.String(http.StatusOK, "hello world")
}
main:
func main() {
server, err := api.Register()
if server != nil {
server.Run(":8081")
} else {
fmt.Println("fail to start server, for reason:/n" + err.Error())
}
}