-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1286 lines (1104 loc) · 34.6 KB
/
Copy pathmain.go
File metadata and controls
1286 lines (1104 loc) · 34.6 KB
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/gorilla/mux"
"github.com/joho/godotenv"
midtrans "github.com/midtrans/midtrans-go"
"github.com/midtrans/midtrans-go/snap"
)
type Collection struct {
Number int `json:"number"`
Arab string `json:"arab"`
ID string `json:"id"`
Explanation string `json:"explanation,omitempty"`
}
type CollectionInfo struct {
Name string `json:"name"`
Slug string `json:"slug"`
Total int `json:"total"`
}
type HadithData struct {
// Only keep collection info in memory (very small ~10KB)
Info []CollectionInfo
mu sync.RWMutex
}
type Pagination struct {
CurrentPage int
TotalPages int
PerPage int
TotalItems int
HasNext bool
HasPrev bool
}
type SearchResult struct {
Collection string `json:"collection"`
Slug string `json:"slug"`
Hadith Collection `json:"hadith"`
Context string `json:"context"`
Score int `json:"score"` // For relevance scoring
}
type SearchFilters struct {
Query string `json:"query"`
Collections []string `json:"collections"`
Language string `json:"language"` // "ar", "id", "all"
NumberRange NumberRange `json:"numberRange"`
SortBy string `json:"sortBy"` // "relevance", "number", "collection"
}
type NumberRange struct {
Min int `json:"min"`
Max int `json:"max"`
}
type FilteredResults struct {
Query string
Filters SearchFilters
Results []SearchResult
Pagination Pagination
TotalItems int
Collections []CollectionInfo
}
var (
data *HadithData
tmpl *template.Template
geminiApiKey string
midtransServerKey string
midtransClientKey string
midtransEnvironment string
)
const (
ItemsPerPage = 20
)
func init() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}
geminiApiKey = os.Getenv("GEMINI_API_KEY")
midtransServerKey = os.Getenv("MIDTRANS_SERVER_KEY")
midtransClientKey = os.Getenv("MIDTRANS_CLIENT_KEY")
midtransEnvironment = os.Getenv("MIDTRANS_ENVIRONMENT")
// Initialize Midtrans Snap client
if midtransServerKey != "" {
var environment midtrans.EnvironmentType
if midtransEnvironment == "production" {
environment = midtrans.Production
} else {
environment = midtrans.Sandbox
}
midtrans.ServerKey = midtransServerKey
midtrans.Environment = environment
}
}
func loadData() {
data = &HadithData{
Info: []CollectionInfo{},
}
// Load only collection list (very small ~10KB)
listData, err := ioutil.ReadFile("resource/list.json")
if err != nil {
log.Fatal("Error loading list.json:", err)
}
err = json.Unmarshal(listData, &data.Info)
if err != nil {
log.Fatal("Error parsing list.json:", err)
}
log.Printf("Loaded %d collection info (disk-based mode - very low memory usage)", len(data.Info))
}
// Load a single collection from disk on-demand
func loadCollection(slug string) ([]Collection, error) {
filename := "resource/" + slug + ".json"
collectionData, err := ioutil.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("error loading %s: %v", filename, err)
}
var collection []Collection
err = json.Unmarshal(collectionData, &collection)
if err != nil {
return nil, fmt.Errorf("error parsing %s: %v", filename, err)
}
return collection, nil
}
// Get collection info by slug
func getCollectionInfo(slug string) *CollectionInfo {
for _, info := range data.Info {
if info.Slug == slug {
return &info
}
}
return nil
}
// Template functions
func add(a, b int) int {
return a + b
}
func add1(a int) int {
return a + 1
}
func subtract(a, b int) int {
return a - b
}
func multiply(a, b int) int {
return a * b
}
func formatHadith(s string) template.HTML {
re := regexp.MustCompile(`\[(.*?)\]`)
result := re.ReplaceAllString(s, "<strong>$1</strong>")
return template.HTML(result)
}
func pageNumbers(current, total int) []int {
var pages []int
start := current - 2
if start < 1 {
start = 1
}
end := start + 4
if end > total {
end = total
start = end - 4
if start < 1 {
start = 1
}
}
for page := start; page <= end; page++ {
pages = append(pages, page)
}
return pages
}
func formatRupiah(amount float64) string {
return fmt.Sprintf("Rp %.0f", amount)
}
func calculatePercentage(current float64, target float64) float64 {
if target <= 0 {
return 0
}
percent := (current / target) * 100
if percent > 100 {
return 100
}
return percent
}
func safeHTML(s string) template.HTML {
return template.HTML(s)
}
type SEOData struct {
Title string
Description string
Keywords string
OGImage string
OGUrl string
Canonical string
}
type PageData struct {
SEO SEOData
Data interface{}
Info *CollectionInfo
Hadith *Collection
PrevHadith *Collection
NextHadith *Collection
Collection string
Pagination Pagination
}
func favoritesHandler(w http.ResponseWriter, r *http.Request) {
seo := SEOData{
Title: "Hadits Favorit Saya - hadits.online",
Description: "Daftar hadits pilihan yang Anda simpan untuk dipelajari lebih lanjut.",
Keywords: "hadits favorit, simpan hadits, belajar islam",
OGUrl: "https://hadits.online/favorites",
Canonical: "https://hadits.online/favorites",
}
pageData := PageData{
SEO: seo,
}
tmpl := template.Must(template.ParseFiles("templates/favorites.html", "templates/components/navbar.html", "templates/components/footer.html"))
if err := tmpl.Execute(w, pageData); err != nil {
http.Error(w, "Template error: "+err.Error(), http.StatusInternalServerError)
}
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
// Create a template with custom functions
funcMap := template.FuncMap{
"add": add,
"add1": add1,
"subtract": subtract,
"multiply": multiply,
"pageNumbers": pageNumbers,
"formatHadith": formatHadith,
}
seo := SEOData{
Title: "hadits.online - Pusat Belajar Hadits Terlengkap Bahasa Indonesia",
Description: "Cari dan pelajari ribuan hadits shahih dari Bukhari, Muslim, Abu Daud, dan kitab lainnya dengan terjemahan Indonesia yang akurat.",
Keywords: "hadits online, hadits shahih, bukhari, muslim, terjemahan hadits, belajar islam",
OGUrl: "https://hadits.online/",
Canonical: "https://hadits.online/",
}
pageData := PageData{
SEO: seo,
Data: data.Info,
}
tmpl := template.Must(template.New("index.html").Funcs(funcMap).ParseFiles("templates/index.html", "templates/components/navbar.html", "templates/components/footer.html"))
if err := tmpl.Execute(w, pageData); err != nil {
http.Error(w, "Template error: "+err.Error(), http.StatusInternalServerError)
}
}
func collectionHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
slug := vars["slug"]
// Get collection info
info := getCollectionInfo(slug)
if info == nil {
http.Error(w, "Collection not found", http.StatusNotFound)
return
}
// Load collection from disk on-demand
collection, err := loadCollection(slug)
if err != nil {
http.Error(w, "Error loading collection: "+err.Error(), http.StatusInternalServerError)
return
}
// Get pagination parameters
page := 1
if pageStr := r.URL.Query().Get("page"); pageStr != "" {
if p, err := strconv.Atoi(pageStr); err == nil && p > 0 {
page = p
}
}
// Calculate pagination
totalItems := len(collection)
totalPages := (totalItems + ItemsPerPage - 1) / ItemsPerPage
startIndex := (page - 1) * ItemsPerPage
endIndex := startIndex + ItemsPerPage
if startIndex >= totalItems {
startIndex = 0
endIndex = ItemsPerPage
page = 1
}
if endIndex > totalItems {
endIndex = totalItems
}
paginatedHadiths := collection[startIndex:endIndex]
pagination := Pagination{
CurrentPage: page,
TotalPages: totalPages,
PerPage: ItemsPerPage,
TotalItems: totalItems,
HasNext: page < totalPages,
HasPrev: page > 1,
}
seo := SEOData{
Title: fmt.Sprintf("Koleksi Hadits %s - hadits.online", info.Name),
Description: fmt.Sprintf("Daftar lengkap hadits dari kitab %s. Tersedia %d hadits dengan terjemahan Indonesia.", info.Name, info.Total),
Keywords: fmt.Sprintf("hadits %s, kitab %s, kumpulan hadits", info.Name, info.Name),
OGUrl: fmt.Sprintf("https://hadits.online/collection/%s", slug),
Canonical: fmt.Sprintf("https://hadits.online/collection/%s", slug),
}
pageData := PageData{
SEO: seo,
Info: info,
Data: paginatedHadiths,
Collection: slug,
Pagination: pagination,
}
// Create template with custom functions
funcMap := template.FuncMap{
"add": add,
"add1": add1,
"subtract": subtract,
"multiply": multiply,
"pageNumbers": pageNumbers,
"formatHadith": formatHadith,
}
tmpl := template.Must(template.New("collection.html").Funcs(funcMap).ParseFiles("templates/collection.html", "templates/components/navbar.html", "templates/components/footer.html"))
if err := tmpl.Execute(w, pageData); err != nil {
http.Error(w, "Template error: "+err.Error(), http.StatusInternalServerError)
}
}
func hadithHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
slug := vars["slug"]
numberStr := vars["number"]
// Load collection from disk on-demand
collection, err := loadCollection(slug)
if err != nil {
http.Error(w, "Error loading collection: "+err.Error(), http.StatusInternalServerError)
return
}
// Find hadith by number
number, err := strconv.Atoi(numberStr)
if err != nil {
http.Error(w, "Invalid hadith number", http.StatusBadRequest)
return
}
var hadith *Collection
var hadithIndex int
for i, h := range collection {
if h.Number == number {
hadith = &h
hadithIndex = i
break
}
}
if hadith == nil {
http.Error(w, "Hadith not found", http.StatusNotFound)
return
}
// Get collection info
info := getCollectionInfo(slug)
if info == nil {
http.Error(w, "Collection info not found", http.StatusNotFound)
return
}
var prevHadith, nextHadith *Collection
if hadithIndex > 0 {
prevHadith = &collection[hadithIndex-1]
}
if hadithIndex < len(collection)-1 {
nextHadith = &collection[hadithIndex+1]
}
description := hadith.ID
if len(description) > 160 {
description = description[:157] + "..."
}
seo := SEOData{
Title: fmt.Sprintf("Hadits %s No. %d - hadits.online", info.Name, hadith.Number),
Description: description,
Keywords: fmt.Sprintf("hadits %s %d, %s no %d", info.Name, hadith.Number, info.Name, hadith.Number),
OGUrl: fmt.Sprintf("https://hadits.online/collection/%s/%d", slug, hadith.Number),
Canonical: fmt.Sprintf("https://hadits.online/collection/%s/%d", slug, hadith.Number),
}
pageData := PageData{
SEO: seo,
Info: info,
Hadith: hadith,
PrevHadith: prevHadith,
NextHadith: nextHadith,
}
// Create template with custom functions
funcMap := template.FuncMap{
"add": add,
"add1": add1,
"subtract": subtract,
"multiply": multiply,
"pageNumbers": pageNumbers,
"formatHadith": formatHadith,
}
tmpl := template.Must(template.New("hadith.html").Funcs(funcMap).ParseFiles("templates/hadith.html", "templates/components/navbar.html", "templates/components/footer.html"))
if err := tmpl.Execute(w, pageData); err != nil {
http.Error(w, "Template error: "+err.Error(), http.StatusInternalServerError)
}
}
func searchHandler(w http.ResponseWriter, r *http.Request) {
// Parse filters
filters := parseSearchFilters(r)
// Validate query
if filters.Query == "" {
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
// Get pagination parameters
page := 1
if pageStr := r.URL.Query().Get("page"); pageStr != "" {
if p, err := strconv.Atoi(pageStr); err == nil && p > 0 {
page = p
}
}
// Perform advanced search
allResults := performAdvancedSearch(filters)
totalItems := len(allResults)
// Calculate pagination
totalPages := (totalItems + ItemsPerPage - 1) / ItemsPerPage
if page > totalPages && totalPages > 0 {
page = totalPages
}
if page < 1 {
page = 1
}
startIndex := (page - 1) * ItemsPerPage
endIndex := startIndex + ItemsPerPage
if startIndex < 0 {
startIndex = 0
}
if startIndex > totalItems {
startIndex = totalItems
}
if endIndex > totalItems {
endIndex = totalItems
}
var paginatedResults []SearchResult
if totalItems > 0 {
paginatedResults = allResults[startIndex:endIndex]
}
pagination := Pagination{
CurrentPage: page,
TotalPages: totalPages,
PerPage: ItemsPerPage,
TotalItems: totalItems,
HasNext: page < totalPages,
HasPrev: page > 1,
}
seo := SEOData{
Title: fmt.Sprintf("Hasil Pencarian: %s - hadits.online", filters.Query),
Description: fmt.Sprintf("Temukan %d hadits terkait %s di hadits.online.", totalItems, filters.Query),
Keywords: fmt.Sprintf("cari hadits %s, hasil pencarian %s", filters.Query, filters.Query),
OGUrl: fmt.Sprintf("https://hadits.online/search?q=%s", filters.Query),
Canonical: fmt.Sprintf("https://hadits.online/search?q=%s", filters.Query),
}
pageData := struct {
SEO SEOData
Query string
Filters SearchFilters
Results []SearchResult
Pagination Pagination
TotalItems int
Collections []CollectionInfo
}{
SEO: seo,
Query: filters.Query,
Filters: filters,
Results: paginatedResults,
Pagination: pagination,
TotalItems: totalItems,
Collections: data.Info,
}
// Create template with custom functions
funcMap := template.FuncMap{
"add": add,
"add1": add1,
"subtract": subtract,
"multiply": multiply,
"pageNumbers": pageNumbers,
"formatHadith": formatHadith,
"urlEncode": func(s string) string {
result := strings.ReplaceAll(s, " ", "+")
result = strings.ReplaceAll(result, "&", "%26")
result = strings.ReplaceAll(result, "=", "%3D")
return result
},
"hasFilter": func(slice []string, item string) bool {
for _, v := range slice {
if v == item {
return true
}
}
return false
},
"buildFilterURL": func(query string, filters SearchFilters, page int) string {
params := []string{}
if query != "" {
params = append(params, "q="+strings.ReplaceAll(query, " ", "+"))
}
if filters.Language != "" && filters.Language != "all" {
params = append(params, "lang="+filters.Language)
}
if filters.SortBy != "" && filters.SortBy != "relevance" {
params = append(params, "sort="+filters.SortBy)
}
if len(filters.Collections) > 0 {
collections := strings.Join(filters.Collections, ",")
params = append(params, "collections="+collections)
}
if filters.NumberRange.Min > 0 {
params = append(params, fmt.Sprintf("min=%d", filters.NumberRange.Min))
}
if filters.NumberRange.Max > 0 {
params = append(params, fmt.Sprintf("max=%d", filters.NumberRange.Max))
}
if page > 1 {
params = append(params, fmt.Sprintf("page=%d", page))
}
if len(params) > 0 {
return "/search?" + strings.Join(params, "&")
}
return "/search"
},
}
tmpl := template.Must(template.New("search.html").Funcs(funcMap).ParseFiles("templates/search.html", "templates/components/navbar.html", "templates/components/footer.html"))
if err := tmpl.Execute(w, pageData); err != nil {
log.Printf("Template execution error in searchHandler: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}
// Helper function to highlight search terms
func highlightText(text, query string) string {
if query == "" {
return text
}
// Simple highlighting - in production you'd want more sophisticated highlighting
words := strings.Fields(strings.ToLower(query))
result := text
for _, word := range words {
if len(word) > 2 { // Only highlight words longer than 2 characters
// This is a simple case-insensitive replacement
// In production, you'd want better HTML escaping and matching
result = strings.ReplaceAll(result, word,
"<mark class='bg-yellow-200 px-1 rounded'>"+word+"</mark>")
}
}
return result
}
// Advanced filtering functions
func parseSearchFilters(r *http.Request) SearchFilters {
filters := SearchFilters{
Query: strings.ToLower(strings.TrimSpace(r.URL.Query().Get("q"))),
Language: r.URL.Query().Get("lang"),
SortBy: r.URL.Query().Get("sort"),
}
// Parse collections filter
collectionsParam := r.URL.Query().Get("collections")
if collectionsParam != "" {
filters.Collections = strings.Split(collectionsParam, ",")
// Clean up collection names
for i, col := range filters.Collections {
filters.Collections[i] = strings.TrimSpace(col)
}
}
// Parse number range
minStr := r.URL.Query().Get("min")
maxStr := r.URL.Query().Get("max")
if minStr != "" || maxStr != "" {
filters.NumberRange = NumberRange{}
if minStr != "" {
if min, err := strconv.Atoi(minStr); err == nil {
filters.NumberRange.Min = min
}
}
if maxStr != "" {
if max, err := strconv.Atoi(maxStr); err == nil {
filters.NumberRange.Max = max
}
}
}
// Set defaults
if filters.Language == "" {
filters.Language = "all"
}
if filters.SortBy == "" {
filters.SortBy = "relevance"
}
return filters
}
func calculateRelevanceScore(arabText, idText string, query string, queryWords []string) int {
score := 0
// Exact match gets highest score (only check once)
if strings.Contains(arabText, query) || strings.Contains(idText, query) {
score += 100
}
// Check for partial matches (optimized with pre-split words)
for _, word := range queryWords {
if len(word) > 2 {
if strings.Contains(arabText, word) {
score += 20
}
if strings.Contains(idText, word) {
score += 15
}
}
}
// Boost score if query is in ID (Indonesian translation) - combined with above
if strings.Contains(idText, query) {
score += 30
}
// Boost score if query is in Arabic - combined with above
if strings.Contains(arabText, query) {
score += 25
}
return score
}
func matchesFilter(arabText, idText string, hadithNumber int, slug string, filters SearchFilters, query string, queryWords []string) bool {
// Collection filter (early exit)
if len(filters.Collections) > 0 {
found := false
for _, col := range filters.Collections {
if strings.EqualFold(col, slug) {
found = true
break
}
}
if !found {
return false
}
}
// Query match check - optimized with pre-lowered text and query
queryMatched := false
if filters.Language == "ar" {
queryMatched = strings.Contains(arabText, query)
} else if filters.Language == "id" {
queryMatched = strings.Contains(idText, query)
} else {
// Default "all" or anything else: check both
queryMatched = strings.Contains(arabText, query) || strings.Contains(idText, query)
}
// Also check individual words for better matching (word-level search)
if !queryMatched && len(queryWords) > 0 {
for _, word := range queryWords {
if len(word) > 2 {
if strings.Contains(arabText, word) || strings.Contains(idText, word) {
queryMatched = true
break
}
}
}
}
if !queryMatched {
return false
}
// Number range filter (early exit)
if filters.NumberRange.Min > 0 && hadithNumber < filters.NumberRange.Min {
return false
}
if filters.NumberRange.Max > 0 && hadithNumber > filters.NumberRange.Max {
return false
}
return true
}
func sortResults(results []SearchResult, sortBy string) {
switch sortBy {
case "number":
// Sort by hadith number within collections
sort.Slice(results, func(i, j int) bool {
if results[i].Slug != results[j].Slug {
return results[i].Slug < results[j].Slug
}
return results[i].Hadith.Number < results[j].Hadith.Number
})
case "collection":
// Sort by collection name
sort.Slice(results, func(i, j int) bool {
return results[i].Slug < results[j].Slug
})
default: // relevance
sort.Slice(results, func(i, j int) bool {
return results[i].Score > results[j].Score
})
}
}
// Disk-based search - loads collections from disk on-demand (minimal memory usage)
func performAdvancedSearch(filters SearchFilters) []SearchResult {
lowerQuery := strings.ToLower(filters.Query)
queryWords := strings.Fields(lowerQuery)
// Pre-allocate results slice with memory limit
maxResults := 500
allResults := make([]SearchResult, 0, 100)
data.mu.RLock()
defer data.mu.RUnlock()
// Get collections to search (based on filter)
var collectionsToSearch []CollectionInfo
if len(filters.Collections) > 0 {
// Filter collections
for _, col := range filters.Collections {
for _, info := range data.Info {
if strings.EqualFold(col, info.Slug) {
collectionsToSearch = append(collectionsToSearch, info)
break
}
}
}
} else {
// Search all collections
collectionsToSearch = data.Info
}
// Search each collection (disk-based)
for _, info := range collectionsToSearch {
// Load collection from disk on-demand
collection, err := loadCollection(info.Slug)
if err != nil {
log.Printf("Error loading collection %s: %v", info.Slug, err)
continue
}
// Search within this collection
for _, hadith := range collection {
// Limit results
if len(allResults) >= maxResults {
break
}
// Pre-lower texts
lowerArab := strings.ToLower(hadith.Arab)
lowerID := strings.ToLower(hadith.ID)
// Check if matches filters
if matchesFilter(lowerArab, lowerID, hadith.Number, info.Slug, filters, lowerQuery, queryWords) {
// Calculate score
score := calculateRelevanceScore(lowerArab, lowerID, lowerQuery, queryWords)
// Get context
context := hadith.ID
if len(context) > 300 {
context = context[:300] + "..."
}
allResults = append(allResults, SearchResult{
Collection: info.Name,
Slug: info.Slug,
Hadith: hadith,
Context: context,
Score: score,
})
}
}
// Early exit if we have enough results
if len(allResults) >= maxResults {
break
}
}
// Sort results
if len(allResults) > 0 {
sortResults(allResults, filters.SortBy)
}
return allResults
}
// Helper function to get page URL
func getPageURL(baseURL string, page int) string {
if page == 1 {
return baseURL
}
separator := "?"
if strings.Contains(baseURL, "?") {
separator = "&"
}
return baseURL + separator + "page=" + strconv.Itoa(page)
}
func robotsHandler(w http.ResponseWriter, r *http.Request) {
content := "User-agent: *\nAllow: /\nSitemap: https://hadits.online/sitemap.xml"
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte(content))
}
func sitemapHandler(w http.ResponseWriter, r *http.Request) {
var sb strings.Builder
sb.WriteString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
sb.WriteString("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n")
// Home
sb.WriteString(" <url>\n <loc>https://hadits.online/</loc>\n <priority>1.0</priority>\n </url>\n")
sb.WriteString(" <url>\n <loc>https://hadits.online/donate</loc>\n <priority>0.5</priority>\n </url>\n")
sb.WriteString(" <url>\n <loc>https://hadits.online/faq</loc>\n <priority>0.5</priority>\n </url>\n")
// Collections (disk-based - load each collection individually)
data.mu.RLock()
for _, info := range data.Info {
sb.WriteString(fmt.Sprintf(" <url>\n <loc>https://hadits.online/collection/%s</loc>\n <priority>0.8</priority>\n </url>\n", info.Slug))
// Load collection for individual hadith URLs
collection, err := loadCollection(info.Slug)
if err != nil {
log.Printf("Error loading collection %s for sitemap: %v", info.Slug, err)
continue
}
// Individual Hadiths (limited to first 100 to keep sitemap small and fast)
// You can increase this if needed, but for disk-based mode, limiting is better
limit := 100
for i, h := range collection {
if i >= limit {
break
}
sb.WriteString(fmt.Sprintf(" <url>\n <loc>https://hadits.online/collection/%s/%d</loc>\n <priority>0.6</priority>\n </url>\n", info.Slug, h.Number))
}
}
data.mu.RUnlock()
sb.WriteString("</urlset>")
w.Header().Set("Content-Type", "application/xml")
w.Write([]byte(sb.String()))
}
func main() {
log.Println("Loading hadith data...")
loadData()
log.Println("Data loaded successfully")
r := mux.NewRouter()
// Routes with better error handling
r.HandleFunc("/", homeHandler)
r.HandleFunc("/favorites", favoritesHandler)
r.HandleFunc("/collection/{slug}", collectionHandler)
r.HandleFunc("/collection/{slug}/{number}", hadithHandler)
r.HandleFunc("/search", searchHandler)
r.HandleFunc("/api/explain", explainHandler)
r.HandleFunc("/donate", donateHandler)
r.HandleFunc("/api/midtrans/token", midtransTokenHandler)
r.HandleFunc("/faq", faqHandler)
r.HandleFunc("/robots.txt", robotsHandler)
r.HandleFunc("/sitemap.xml", sitemapHandler)
r.HandleFunc("/manifest.json", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "static/manifest.json")
})
r.HandleFunc("/service-worker.js", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "static/service-worker.js")
})
// Serve static files
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("static/"))))
// Serve index.html at root
r.HandleFunc("/index.html", homeHandler)
// Add 404 handler
r.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
tmpl := template.Must(template.ParseFiles("templates/404.html", "templates/components/navbar.html", "templates/components/footer.html"))
seo := SEOData{
Title: "Halaman Tidak Ditemukan - hadits.online",
Description: "Maaf, halaman yang Anda cari tidak dapat ditemukan.",
}
tmpl.Execute(w, struct {
SEO SEOData
Path string
}{SEO: seo, Path: r.URL.Path})
})
log.Println("Server starting on :8082")
log.Println("Access the application at: http://localhost:8082")
log.Fatal(http.ListenAndServe(":8082", r))
}
type GeminiPart struct {
Text string `json:"text"`
}
type GeminiContent struct {
Parts []GeminiPart `json:"parts"`
}
type GeminiRequest struct {
Contents []GeminiContent `json:"contents"`
SystemInstruction GeminiContent `json:"system_instruction,omitempty"`
}
type GeminiResponse struct {
Candidates []struct {
Content GeminiContent `json:"content"`
} `json:"candidates"`
}
func explainHandler(w http.ResponseWriter, r *http.Request) {
if geminiApiKey == "" {