在Ubuntu上配置Swagger可以分為幾個步驟,具體如下:
首先,確保你的系統上已經安裝了Node.js和HTTP Server。如果還沒有安裝Node.js,可以參考Node.js的官方安裝教程進行安裝。
# 新建swagger目錄
mkdir /opt/swagger
# 進入該目錄
cd /opt/swagger
# 下載swagger-editor最新版本
wget https://github.com/swagger-api/swagger-editor/archive/refs/tags/v3.16.1.tar.gz
# 解壓
tar -xvf v3.16.1.tar.gz
# 刪除壓縮文件
rm v3.16.1.tar.gz
# 安裝 Node.js 和 HttpServer
npm install -g http-server
安裝完成后,在swagger目錄中執行以下命令啟動服務:
http-server -p 8081
然后訪問 http://127.0.0.1:8081
來確認是否可以訪問 Swagger Editor。
回到swagger目錄,下載并解壓Swagger UI的最新版本:
cd /opt/swagger
wget https://github.com/swagger-api/swagger-ui/archive/refs/tags/v3.48.0.tar.gz
tar -xvf v3.48.0.tar.gz
rm v3.48.0.tar.gz
初始化Node.js項目并安裝Express:
npm init -y
npm install express --save
在項目根目錄下創建一個名為 index.js
的文件,并添加以下內容:
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname)));
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
然后啟動HTTP Server:
node index.js
訪問 http://127.0.0.1:3000
來確認是否可以訪問 Swagger UI。
如果你使用的是Spring Boot項目,可以使用springfox-swagger2
和springfox-swagger-ui
來集成Swagger。
在項目的pom.xml
文件中添加以下依賴:
<dependencies>
<!-- Swagger 2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>YOUR_DESIRED_VERSION</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>YOUR_DESIRED_VERSION</version>
</dependency>
<!-- 其他依賴 -->
</dependencies>
替換YOUR_DESIRED_VERSION
為實際使用的版本號。
創建一個配置類來啟用Swagger并定義一些基本信息:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
這個配置類啟用了Swagger,并告訴Swagger掃描所有的API接口來生成文檔。
啟動Spring Boot項目后,訪問 http://localhost:8080/swagger-ui.html
(假設服務端口為8080),可以看到Swagger UI界面,其中展示了項目中定義的所有API接口及其詳細信息。
通過以上步驟,你就可以在Ubuntu上成功配置Swagger。根據你的項目類型(Spring Boot或其他),選擇相應的配置方法即可。