go 基于beego+swagger生成支持直接调用的接口文档

安装工具

go get github.com/astaxie/beego
go get github.com/beego/bee

创建API项目

# 必须在GOPATH下创建项目,否则无法在routers目录下生成commentsRouter_controllers.go,访问URL会报错404
cd $GOPATH
bee api swagger-test
cd swagger-test
bee run -gendoc=true -downdoc=true

新增GET接口

1. models中新增student.go

package models

import (
	"errors"
)

type Student struct {
	Id   string
	Name string
	Age  int
}

func GetStudent(id string) (*Student, error) {
	if id != "test" {
		return nil, errors.New("this student not exist")
	}
	return &Student{
		Id:   "test",
		Name: "test",
		Age:  100,
	}, nil
}

2. controllers中新增student.go

package controllers

import (
	"swagger-test/models"

	"github.com/astaxie/beego"
)

type StudentController struct {
	beego.Controller
}

// @Title GetStudent
// @Description get student by id
// @Param	studentId		path 	string	true "id"
// @Success 200 {student} models.Student
// @Failure 400 studentId is empty
// @router /:studentId [get]
func (s *StudentController) Get() {
	id := s.Ctx.Input.Param(":studentId")
	if id != "" {
		student, err := models.GetStudent(id)
		if err != nil {
			s.Data["json"] = err.Error()
		} else {
			s.Data["json"] = student
		}
	}
	s.ServeJSON()
}

3. routers中修改router.go

// 增加
beego.NSNamespace("/student",
	beego.NSInclude(
		&controllers.StudentController{},
	),
),

效果

http://127.0.0.1:8080/swagger/

posted on 2025-05-31 23:04  王景迁  阅读(19)  评论(0)    收藏  举报

导航