AdSense

網頁

2023/4/16

Golang Swagger enums標記

Go swagger使用enums標記欄位允許得值。


範例環境:

  • go 1.17
  • github.com/swaggo/swag v1.8.3

例如下面建立員工API request body的CreateEmployeeRequest.Title僅接受"engineer"及"manager"兩種值,所以在欄位後面加上enums:"engineer,manager"標記,則在產生Swagger UI文件時會在參數的model中顯示。

view.go

package view

import "time"

type CreateEmployeeRequest struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
    // Employee title:
    // * engineer - developer, programer.
    // * manager - product manger, project manager, supervisor.
    Title string `json:"title" enums:"engineer,manager"`
}

type CreateEmployeeResponse struct {
    Id        string    `json:"id"`
    CreatedAt time.Time `json:"createdAt"`
}

main.go

package main

import (
    "fmt"
    "net/http"

    _ "abc.com/demo/docs"
    httpSwagger "github.com/swaggo/http-swagger"
)

// @contact.name   菜鳥工程師肉豬
// @contact.url    https://matthung0807.blogspot.com/
// @title Swagger Demo
// @version 1.0
// @description Swagger API.
// @host localhost:8080
func main() {
    http.HandleFunc("/hello", HelloHandler)
    http.HandleFunc("/employee", CreateEmployeeHandler)
    http.HandleFunc("/swagger/", httpSwagger.WrapHandler)

    http.ListenAndServe(":8080", nil)
}

// @Tags Hello
// @Produce plain
// @Param name query string false "user name"
// @Success 200 {string} string "ok"
// @Router /hello [get]
func HelloHandler(rw http.ResponseWriter, r *http.Request) {
    name := r.URL.Query().Get("name")
    content := fmt.Sprintf("hello, %s", name)
    fmt.Fprint(rw, content)
}

// @Summary Create a new employee
// @Description Create a new employee
// @Tags employee
// @Produce json
// @param request body view.CreateEmployeeRequest true "create params"
// @Success 200 {object} view.CreateEmployeeResponse
// @Router /employee [post]
func CreateEmployeeHandler(rw http.ResponseWriter, r *http.Request) {
}

github





沒有留言:

AdSense