mirror of
https://codeberg.org/video-prize-ranch/rimgo.git
synced 2026-01-27 17:11:13 +00:00
* use encoding/json for comment parsing * refactor by moving loop code to an UnmarshalJSON * use a preallocated array and indices to maintain order while using goroutines again, this was removed a while ago * use new struct in comment.hbs and contextComment.hbs * rewriteUrl partial to reduce rimgo-specific code in api * move RenderError into pages package to avoid import cycle between render and utils
84 lines
1.8 KiB
Go
84 lines
1.8 KiB
Go
package utils
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/tidwall/gjson"
|
|
)
|
|
|
|
func GetJSONNew(url string) (json.RawMessage, error) {
|
|
req, err := http.NewRequest("GET", url, nil)
|
|
if err != nil {
|
|
return json.RawMessage{}, err
|
|
}
|
|
|
|
SetReqHeaders(req)
|
|
|
|
client := http.Client{}
|
|
res, err := client.Do(req)
|
|
if err != nil {
|
|
return json.RawMessage{}, err
|
|
}
|
|
rateLimitRemaining := res.Header.Get("X-RateLimit-UserRemaining")
|
|
if rateLimitRemaining != "" {
|
|
ratelimit, _ := strconv.Atoi(rateLimitRemaining)
|
|
if ratelimit <= 0 {
|
|
return json.RawMessage{}, fmt.Errorf("ratelimited by imgur")
|
|
}
|
|
}
|
|
|
|
body, err := io.ReadAll(res.Body)
|
|
if err != nil {
|
|
return json.RawMessage{}, err
|
|
}
|
|
|
|
switch res.StatusCode {
|
|
case 200:
|
|
return body, nil
|
|
case 429:
|
|
return json.RawMessage{}, fmt.Errorf("ratelimited by imgur")
|
|
default:
|
|
return json.RawMessage{}, fmt.Errorf("received status %s, expected 200 OK.\n%s", res.Status, string(body))
|
|
}
|
|
}
|
|
|
|
func GetJSON(url string) (gjson.Result, error) {
|
|
req, err := http.NewRequest("GET", url, nil)
|
|
if err != nil {
|
|
return gjson.Result{}, err
|
|
}
|
|
|
|
SetReqHeaders(req)
|
|
|
|
client := http.Client{}
|
|
res, err := client.Do(req)
|
|
if err != nil {
|
|
return gjson.Result{}, err
|
|
}
|
|
rateLimitRemaining := res.Header.Get("X-RateLimit-UserRemaining")
|
|
if rateLimitRemaining != "" {
|
|
ratelimit, _ := strconv.Atoi(rateLimitRemaining)
|
|
if ratelimit <= 0 {
|
|
return gjson.Result{}, fmt.Errorf("ratelimited by imgur")
|
|
}
|
|
}
|
|
|
|
body, err := io.ReadAll(res.Body)
|
|
if err != nil {
|
|
return gjson.Result{}, err
|
|
}
|
|
|
|
switch res.StatusCode {
|
|
case 200:
|
|
return gjson.Parse(string(body)), nil
|
|
case 429:
|
|
return gjson.Result{}, fmt.Errorf("ratelimited by imgur")
|
|
default:
|
|
return gjson.Result{}, fmt.Errorf("received status %s, expected 200 OK.\n%s", res.Status, string(body))
|
|
}
|
|
}
|