OpenAPI 4

Submitted by Lizhe on Wed, 11/18/2020 - 07:26

go-swagger 会自动查找程序 main 函数入口

然后生成对应的 swagger 文档

也就是说,endpoint 入口是可以,也应该被分开写在不同文件内的

main.go

 

// Package Helloworld API.

//

// The purpose of this service is to provide an application

// that is using plain go code to define an API

//

//      Host: localhost

//      Version: 0.0.1

//

// swagger:meta

package main

 

import (

    "log"

    "net/http"

)

 

func main() {

    http.HandleFunc("/hello", handlers.Hello)

    if err := http.ListenAndServe(":8080", nil); err != nil {

        log.Fatal(err)

    }

 

HelloHandler.go

 

package handler

 

import (

    "encoding/json"

    "io"

    "net/http"

)

 

// swagger:operation GET /hello tag1 tag2 login

//

// Returns all pets from the system that the user has access to

//

// Could be any pet

//

// ---

// produces:

// - application/json

// parameters:

// - name: name

//   in: query

//   description: user name

//   required: true

//   type: string

// - name: password

//   in: query

//   description: user password

//   required: true

//   type: string

// responses:

//   '200':

//     description: login success

//     schema:

//       type: object

//       items:

//         "$ref": "#/responses/HelloResponse"

//   default:

//     description: unexpected error

//     type: object

//     schema:

//       "$ref": "#/responses/HelloResponse"

func Hello(w http.ResponseWriter, r *http.Request) {

    resp := ResponseMessage{Message: "hello world"}

    res_json, _ := json.Marshal(resp)

    io.WriteString(w, string(res_json))

}

 

// HelloResponse is an response with helloworld message.

//

// swagger:response HelloResponse

type ResponseMessage struct {

    Message string

}

 

 

 

20201118034731