reduce code by using library

This commit is contained in:
Ted Unangst 2019-07-28 19:54:39 -04:00
parent 7e1bf702cc
commit a6b45e4c92
1 changed files with 5 additions and 56 deletions

View File

@ -17,8 +17,6 @@ package main
import ( import (
"bytes" "bytes"
"compress/gzip"
"context"
"crypto/rsa" "crypto/rsa"
"database/sql" "database/sql"
"fmt" "fmt"
@ -87,20 +85,6 @@ func PostMsg(keyname string, key *rsa.PrivateKey, url string, msg []byte) error
return nil return nil
} }
type gzCloser struct {
r *gzip.Reader
under io.ReadCloser
}
func (gz *gzCloser) Read(p []byte) (int, error) {
return gz.r.Read(p)
}
func (gz *gzCloser) Close() error {
defer gz.under.Close()
return gz.r.Close()
}
func GetJunk(url string) (junk.Junk, error) { func GetJunk(url string) (junk.Junk, error) {
return GetJunkTimeout(url, 0) return GetJunkTimeout(url, 0)
} }
@ -110,50 +94,15 @@ func GetJunkFast(url string) (junk.Junk, error) {
} }
func GetJunkTimeout(url string, timeout time.Duration) (junk.Junk, error) { func GetJunkTimeout(url string, timeout time.Duration) (junk.Junk, error) {
client := http.DefaultClient
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
at := thefakename at := thefakename
if strings.Contains(url, ".well-known/webfinger?resource") { if strings.Contains(url, ".well-known/webfinger?resource") {
at = "application/jrd+json" at = "application/jrd+json"
} }
req.Header.Set("Accept", at) return junk.Get(url, junk.GetArgs{
req.Header.Set("Accept-Encoding", "gzip") Accept: at,
req.Header.Set("User-Agent", "honksnonk/5.0; "+serverName) Agent: "honksnonk/5.0; " + serverName,
if timeout > 0 { Timeout: timeout,
ctx, cancel := context.WithTimeout(context.Background(), timeout) })
defer cancel()
req = req.WithContext(ctx)
}
resp, err := client.Do(req)
if err != nil {
if timeout > 0 || !strings.Contains(err.Error(), "TLS handshake timeout") {
return nil, err
}
log.Printf("first get failed: %s", err)
resp, err = client.Do(req)
if err != nil {
return nil, err
}
log.Printf("retry succeeded!")
}
if resp.StatusCode != 200 {
resp.Body.Close()
return nil, fmt.Errorf("http get status: %d", resp.StatusCode)
}
if strings.EqualFold(resp.Header.Get("Content-Encoding"), "gzip") {
gz, err := gzip.NewReader(resp.Body)
if err != nil {
resp.Body.Close()
return nil, err
}
resp.Body = &gzCloser{r: gz, under: resp.Body}
}
defer resp.Body.Close()
j, err := junk.Read(resp.Body)
return j, err
} }
func savedonk(url string, name, media string, localize bool) *Donk { func savedonk(url string, name, media string, localize bool) *Donk {