golang-nacos-api-demo
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

112 lines
2.4 KiB

package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/nacos-group/nacos-sdk-go/clients"
"github.com/nacos-group/nacos-sdk-go/common/constant"
"github.com/nacos-group/nacos-sdk-go/vo"
"log"
"net"
"net/http"
"os"
"strconv"
"strings"
)
var port = "8888"
func initNacos() {
sc := []constant.ServerConfig{
*constant.NewServerConfig("nacos-headless", 8848),
}
cc := constant.ClientConfig{
AppName: "api1",
NamespaceId: "", //namespace id
TimeoutMs: 5000,
NotLoadCacheAtStart: true,
RotateTime: "1h",
MaxAge: 3,
LogLevel: "debug",
}
configParam := vo.NacosClientParam{
ClientConfig: &cc,
ServerConfigs: sc,
}
client, err := clients.NewNamingClient(configParam)
if err != nil {
panic(err)
}
portNum, _ := strconv.Atoi(port)
pp := uint64(portNum)
12 months ago
success, err := client.RegisterInstance(vo.RegisterInstanceParam{
12 months ago
//Ip: "172.30.0.90",
Port: pp,
Weight: 10,
Enable: true,
ServiceName: "api1",
})
log.Println("Nacos注册结果: ", success)
12 months ago
if err != nil {
log.Println("Nacos注册错误信息: ", err.Error())
}
configClient, err := clients.NewConfigClient(configParam)
if err != nil {
log.Fatalf("创建配置连接失败: %v", err.Error())
}
_ = configClient.ListenConfig(vo.ConfigParam{
DataId: "api.yml",
Group: "DEFAULT_GROUP",
OnChange: func(namespace, group, dataId, data string) {
fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data)
},
})
//log.Println("监听配置失败: ", err.Error())
}
func getIps() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return ""
}
var aaaa []string
for _, address := range addrs {
// 检查ip地址判断是否回环地址
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
ip := ipnet.IP.String()
fmt.Println(ip)
aaaa = append(aaaa, ip)
}
}
}
ipStr := strings.Join(aaaa, ",")
return ipStr
}
func main() {
args := os.Args
if len(args) > 1 {
port = args[1]
}
app := gin.Default()
initNacos()
app.GET("/hello", func(context *gin.Context) {
context.String(http.StatusOK, "[GET]node01"+port)
})
app.POST("/hello", func(context *gin.Context) {
context.String(http.StatusOK, "[POST]node01"+port)
})
app.GET("/ip", func(context *gin.Context) {
context.String(http.StatusOK, getIps())
})
app.Run(fmt.Sprintf(":%v", port))
}