golang快速入门--web--基于http快速构建restful
程序员文章站
2024-02-03 10:06:16
...
构建web接口
文档参考
依赖安装
go get -u github.com/emicklei/go-restful
go get -u github.com/go-openapi/spec
go get -u github.com/emicklei/go-restful-openapi
样例代码
package main
import (
"fmt"
"github.com/emicklei/go-restful"
restfulspec "github.com/emicklei/go-restful-openapi"
"log"
"net/http"
)
func test(request *restful.Request, response *restful.Response) {
// 测试接口逻辑
_id := request.PathParameter("id") // 获取请求参数
response.WriteEntity([]string{_id})
}
func WebService() *restful.WebService {
// 为接口添加路由
// 以下安装swagger 2.0标准配置
ws := new(restful.WebService)
ws.Path("/api").
Consumes(restful.MIME_JSON, restful.MIME_JSON).
Produces(restful.MIME_JSON, restful.MIME_JSON)
ws.Route(
ws.GET("/test/{id}").
To(test).
Doc("测试").
Param(ws.PathParameter("id", "id测试").DataType("integer").DefaultValue("1")).
Returns(200, "成功", "").
DefaultReturns("成功", []string{"1"}),
)
return ws
}
func main() {
restful.DefaultContainer.Add(WebService())
config := restfulspec.Config{
WebServices: restful.RegisteredWebServices(),
APIPath: "/apidocs.json",
}
restful.DefaultContainer.Add(restfulspec.NewOpenAPIService(config))
http.Handle("/apidocs/", http.StripPrefix("/apidocs/", http.FileServer(http.Dir("./swagger-ui/dist/"))))
cors := restful.CrossOriginResourceSharing{
AllowedHeaders: []string{"Content-Type", "Accept"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"},
CookiesAllowed: false,
Container: restful.DefaultContainer}
restful.DefaultContainer.Filter(cors.Filter)
addr := "127.0.0.1:8089"
fmt.Printf("http://%s/apidocs/?url=http://%s/apidocs.json\n", addr, addr)
log.Fatal(http.ListenAndServe(addr, nil))
}