1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
| package main
import ( "encoding/base64" "github.com/olivere/elastic/v7" "gorm.io/driver/sqlite" "gorm.io/gorm" "io/ioutil" "log" "net/http" "os" "strings" ) import "github.com/gin-gonic/gin"
type Post struct { FilenameMD5 string `json:"filename_md5" gorm:"primaryKey;column:filename_md5"` TitleBase64 string `json:"title_base64" gorm:"column:title_base64" ` Title string `json:"title" gorm:"-" ` ContentBase64 string `json:"content_base64" gorm:"column:content_base64" ` Content string `json:"content" gorm:"-" ` PathBase64 string `json:"path_base64" gorm:"column:path_base64" ` Path string `json:"path" gorm:"-" ` Lang string `json:"lang" gorm:"column:lang" ` Sticky string `json:"sticky" gorm:"column:sticky" ` CreatedAt string `json:"created_at" gorm:"column:created_at" ` UpdatedAt string `json:"updated_at" gorm:"column:updated_at" ` }
func getMapping() string { return ` { "mappings": { "properties": { "title_base64": {"type": "keyword"}, "title": {"type": "text","analyzer": "standard"}, "content_base64": {"type": "keyword"}, "content": {"type": "text","analyzer": "standard"}, "path_base64": {"type": "keyword"}, "path": {"type": "keyword"}, "lang": {"type": "keyword"}, "sticky": {"type": "integer"}, "created_at": {"type": "date"}, "updated_at": {"type": "date"} } } } ` }
var configMap map[string]string = initConfig()
func initConfig() (result map[string]string) { var configFileSrc = "./config.conf" if len(os.Args) != 1 { for _, arg := range os.Args { log.Println("当前遍历的参数:", arg) if strings.HasPrefix(arg, "--config=") { var argList = strings.Split(arg, "=") if len(argList) == 1 { continue } log.Println("成功捕获到自定义配置:", argList[1]) configFileSrc = argList[1] break } } } log.Println("获取配置文件路径 成功:", configFileSrc) result = make(map[string]string) allConfig, _ := ioutil.ReadFile(configFileSrc) log.Println("获取配置文件内容 成功:", string(allConfig)) var allConfigLineList = strings.Split(string(allConfig), "\n") for _, line := range allConfigLineList { var keyAndValue = strings.Split(line, "=") if len(keyAndValue) != 2 { continue } var key = keyAndValue[0] var value = keyAndValue[1] result[key] = value } log.Println("读取配置文件 完成:", result) return result }
var db *gorm.DB = initDB()
func initDB() (result *gorm.DB) { log.Println("获取Sqlite数据库文件路径:", configMap["db"]) if res, err := gorm.Open(sqlite.Open(configMap["db"]), &gorm.Config{}); err != nil { log.Panicln("建立Sqlite数据库连接 失败:", err.Error()) } else { log.Println("建立Sqlite数据库连接 成功:", res) result = res } return result }
var es *elastic.Client = initES()
func initES() (result *elastic.Client) { var url string = "http://" + configMap["es.ip"] + ":" + configMap["es.port"] log.Println("es url:", url) if res, err := elastic.NewClient( elastic.SetSniff(false), elastic.SetURL(url), ); err != nil { log.Panicln("建立ES数据库连接 失败:", err.Error()) } else { log.Println("建立ES数据库连接 成功:", res) result = res } return result }
func main() {
engine := gin.Default()
engine.Handle("GET", "/refresh", func(context *gin.Context) { if context.ClientIP() != "127.0.0.1" { context.JSON(http.StatusOK, "Access denied") return }
var postList []Post if err := db.Find(&postList).Error; err != nil { log.Println("获取Sqlite数据库内的所有数据 失败:", err) } else { }
var indexExist bool if res, err := es.IndexExists(configMap["es.db"]).Do(context); err != nil { log.Println("查询ES的索引是否存在 失败:", err) } else { log.Println("查询ES的索引是否存在 完成:", res) indexExist = res }
if indexExist { if res, err := es.DeleteIndex(configMap["es.db"]).Do(context); err != nil { log.Println("删除ES的索引 失败:", err) } else { log.Println("删除ES的索引 完成:", res) } if res, err := es.CreateIndex(configMap["es.db"]).BodyString(getMapping()).Do(context); err != nil { log.Println("创建ES的索引 失败:", err) } else { log.Println("创建ES的索引 完成:", res) } }
for _, post := range postList {
if title, err := base64.StdEncoding.DecodeString(post.TitleBase64); err != nil { log.Println("Base64解码(TitleBase64) 失败:", err) } else { log.Println("Base64解码(TitleBase64) 成功:", string(title)) post.Title = string(title) } if content, err := base64.StdEncoding.DecodeString(post.ContentBase64); err != nil { log.Println("Base64解码(ContentBase64) 失败:", err) } else { log.Println("Base64解码(ContentBase64) 成功:", string(content)) post.Content = string(content) } if path, err := base64.StdEncoding.DecodeString(post.PathBase64); err != nil { log.Println("Base64解码(PathBase64) 失败:", err) } else { log.Println("Base64解码(PathBase64) 成功:", string(path)) post.Path = string(path) }
if res, err := es.Index().Index(configMap["es.db"]).Id(post.FilenameMD5).BodyJson(post).Do(context); err != nil { log.Println("新增单条文档("+post.FilenameMD5+") 失败:", err) } else { log.Println("新增单条文档("+post.FilenameMD5+") 成功:", res) }
}
context.JSON(http.StatusOK, "Ok") })
engine.Handle("GET", "/search", func(context *gin.Context) { var searchHitList []*elastic.SearchHit if res, err := es.Search().Index(configMap["es.db"]).Do(context); err != nil { log.Println("从ES索引中查询所有文档 失败: err:", err) } else { searchHitList = res.Hits.Hits if len(searchHitList) == 0 { log.Println("从ES索引中查询所有文档 完成: res.Hits.Hits 为空数组") } else { log.Println("从ES索引中查询所有文档 完成: searchHitList:", searchHitList) } }
var resultList []string for _, searchHit := range searchHitList { log.Println("searchHit.Id:", searchHit.Id) if res, err := searchHit.Source.MarshalJSON(); err != nil { log.Println("获取击中的文档数据 失败:", err.Error()) } else { log.Println("获取击中的文档数据 完成:", string(res)) resultList = append(resultList, string(res)) } }
context.JSON(http.StatusOK, resultList) })
engine.Handle("GET", "/search/:keywords", func(context *gin.Context) { var keywords string if res := context.Param("keywords"); res == "" { log.Println("获取关键词 失败: 获取请求参数失败") context.JSON(http.StatusOK, nil) return } else { log.Println("获取关键词 完成:", res) keywords = res }
var searchHitList []*elastic.SearchHit if res, err := es.Search().Index(configMap["es.db"]).Query(elastic.NewMatchPhraseQuery("content", keywords)).Do(context); err != nil { log.Println("根据关键词从ES索引中查询文档 失败: err:", err) } else if res.Error != nil { log.Println("根据关键词从ES索引中查询文档 失败: res.Error:", res.Error) } else { searchHitList = res.Hits.Hits if len(searchHitList) == 0 { log.Println("根据关键词从ES索引中查询文档 完成: res.Hits.Hits 为空数组") } else { log.Println("根据关键词从ES索引中查询文档 完成: searchHitList:", searchHitList) } }
var resultList []string for _, searchHit := range searchHitList { log.Println("searchHit.Id:", searchHit.Id) if res, err := searchHit.Source.MarshalJSON(); err != nil { log.Println("获取击中的文档数据 失败:", err.Error()) } else { log.Println("获取击中的文档数据 完成:", string(res)) resultList = append(resultList, string(res)) } }
context.JSON(http.StatusOK, resultList) })
if err := engine.Run(":" + configMap["app.port"]); err != nil { log.Panicln("Gin启动服务 失败:", err.Error()) } }
|