OpenAPI 2

Submitted by Lizhe on Tue, 11/17/2020 - 08:02

启动Swagger的本地服务器最简单的办法就是 docker

docker pull swaggerapi/swagger-editor

docker run --rm -p 80:8080 swaggerapi/swagger-editor

 

20201117035645

因为实在不喜欢 Java , 这里用 golang 做一个例子

swagger文档的 info 信息,写在package 之前

// 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 (

    "fmt"

    "log"

    "net/http"

)

 

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

    fmt.Fprintf(w, "Hello World")

}

 

func main() {

    http.HandleFunc("/", hello)

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

        log.Fatal(err)

    }

}

 

go get github.com/go-swagger/go-swagger

cd /Users/lizhe/go/src/github.com/go-swagger/go-swagger

go install ./cmd/swagger

20201117051651

 

/Users/lizhe/go/bin/swagger generate spec -o ./swagger.json

20201117052619

 

此时你用本地server打开这个 生成的 json 文件,会得到

20201117052909

 

我们把代码修改一下,返回一个真正的json

 

// 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 (

    "encoding/json"

    "io"

    "log"

    "net/http"

)

 

// swagger:route GET /hello TagHelloworld

//

// Here is summary message

//

// responses:

//  200: 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))

}

 

func main() {

    http.HandleFunc("/hello", hello)

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

        log.Fatal(err)

    }

}

 

// HelloResponse is an response with helloworld message.

//

// swagger:response HelloResponse

type ResponseMessage struct {

    Message string

}

 

 

20201117062128 

 

/Users/lizhe/go/bin/swagger generate spec -o ./swagger.json

20201117062324

 

202081117063039