github.com/mattbailey/reviewdog@v0.10.0/doghouse/client/client.go (about) 1 package client 2 3 import ( 4 "bytes" 5 "context" 6 "encoding/json" 7 "fmt" 8 "io/ioutil" 9 "log" 10 "net/http" 11 "net/url" 12 "os" 13 14 "github.com/reviewdog/reviewdog/commands" 15 "github.com/reviewdog/reviewdog/doghouse" 16 ) 17 18 const baseEndpoint = "https://reviewdog.app" 19 20 // DogHouseClientInterface is interface for doghouse client. 21 type DogHouseClientInterface interface { 22 Check(ctx context.Context, req *doghouse.CheckRequest) (*doghouse.CheckResponse, error) 23 } 24 25 // DogHouseClient is client for doghouse server. 26 type DogHouseClient struct { 27 Client *http.Client 28 // Base URL for API requests. Defaults is https://reviewdog.app 29 BaseURL *url.URL 30 } 31 32 // New returns new DogHouseClient. 33 func New(client *http.Client) *DogHouseClient { 34 dh := &DogHouseClient{Client: client} 35 if dh.Client == nil { 36 dh.Client = http.DefaultClient 37 } 38 base := baseEndpoint 39 if baseEnvURL := os.Getenv("REVIEWDOG_GITHUB_APP_URL"); baseEnvURL != "" { 40 base = baseEnvURL 41 } 42 var err error 43 dh.BaseURL, err = url.Parse(base) 44 if err != nil { 45 log.Fatal(err) 46 } 47 return dh 48 } 49 50 // Check send check requests to doghouse. 51 func (c *DogHouseClient) Check(ctx context.Context, req *doghouse.CheckRequest) (*doghouse.CheckResponse, error) { 52 url := c.BaseURL.String() + "/check" 53 b, err := json.Marshal(req) 54 if err != nil { 55 return nil, err 56 } 57 httpReq, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(b)) 58 if err != nil { 59 return nil, err 60 } 61 httpReq = httpReq.WithContext(ctx) 62 httpReq.Header.Set("Content-Type", "application/json") 63 httpReq.Header.Set("User-Agent", fmt.Sprintf("reviewdog/%s", commands.Version)) 64 65 httpResp, err := c.Client.Do(httpReq) 66 if err != nil { 67 return nil, fmt.Errorf("Check request failed: %v", err) 68 } 69 defer httpResp.Body.Close() 70 71 respb, err := ioutil.ReadAll(httpResp.Body) 72 if err != nil { 73 return nil, err 74 } 75 76 if httpResp.StatusCode != http.StatusOK { 77 return nil, fmt.Errorf("status=%v: %s", httpResp.StatusCode, respb) 78 } 79 80 var resp doghouse.CheckResponse 81 if err := json.Unmarshal(respb, &resp); err != nil { 82 return nil, fmt.Errorf("failed to decode response: error=%v, resp=%s", err, respb) 83 } 84 return &resp, nil 85 }