-
Notifications
You must be signed in to change notification settings - Fork 10
/
main.go
85 lines (81 loc) · 2.05 KB
/
main.go
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
package main
import (
"os"
"strconv"
"github.com/acheong08/DuckDuckGo-API/duckduckgo"
"github.com/acheong08/DuckDuckGo-API/typings"
"github.com/acheong08/endless"
"github.com/gin-gonic/gin"
)
func main() {
HOST := os.Getenv("HOST")
PORT := os.Getenv("PORT")
if PORT == "" {
PORT = "8080"
}
handler := gin.Default()
handler.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
handler.POST("/search", func(ctx *gin.Context) {
// Map request to Search struct
var search typings.Search
if err := ctx.ShouldBindJSON(&search); err != nil {
ctx.JSON(400, gin.H{"error": err.Error(), "details": "Could not bind JSON"})
return
}
// Ensure query is set
if search.Query == "" {
ctx.JSON(400, gin.H{"error": "Query is required"})
return
}
// Get results
results, err := duckduckgo.Get_results(search)
if err != nil {
ctx.JSON(500, gin.H{"error": err.Error()})
return
}
// Limit
if search.Limit > 0 && search.Limit < len(results) {
results = results[:search.Limit]
}
// Return results
ctx.JSON(200, results)
})
handler.GET("/search", func(ctx *gin.Context) {
// Map request to Search struct
var search typings.Search
// Get query
search.Query = ctx.Query("query")
// Get region
search.Region = ctx.Query("region")
// Get time range
search.TimeRange = ctx.Query("time_range")
if search.Query == "" {
ctx.JSON(400, gin.H{"error": "Query is required"})
return
}
// Get limit and check if it's a number
limit := ctx.Query("limit")
if limit != "" {
if _, err := strconv.Atoi(limit); err != nil {
ctx.JSON(400, gin.H{"error": "Limit must be a number"})
return
}
search.Limit, _ = strconv.Atoi(limit)
}
// Get results
results, err := duckduckgo.Get_results(search)
if err != nil {
ctx.JSON(500, gin.H{"error": err.Error()})
return
}
// Shorten results to limit if limit is set
if search.Limit > 0 && search.Limit < len(results) {
results = results[:search.Limit]
}
// Return results
ctx.JSON(200, results)
})
endless.ListenAndServe(HOST+":"+PORT, handler)
}