Skip to content
This repository has been archived by the owner on Mar 22, 2024. It is now read-only.

Commit

Permalink
update token when http status_code ne 200
Browse files Browse the repository at this point in the history
  • Loading branch information
cubatic45 committed Mar 6, 2024
1 parent 997d338 commit 0f6b4e3
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
6 changes: 6 additions & 0 deletions copilot.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ func Init() {
// token return the access token for github copilot
type copiloter interface {
token() (string, error)
refresh() (string, error)
}

func (c *copilot) refresh() (string, error) {
caches.Delete(c.GithubCom.OauthToken)
return c.token()
}

func (c *copilot) token() (string, error) {
Expand Down
14 changes: 11 additions & 3 deletions proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"io"
"net/http"
"os"
"strings"
"time"

Expand Down Expand Up @@ -34,23 +35,27 @@ type Proxy struct {
}

func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
write := io.MultiWriter(w, os.Stdout)
req, err := http.NewRequest(r.Method, r.URL.String(), r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "http request error: %v", err)
fmt.Fprintf(write, "http request error: %v\n", err)
}
if p.Director != nil {
p.Director(req)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "http client error: %v", err)
fmt.Fprintf(write, "http client error: %v\n", err)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
w.WriteHeader(resp.StatusCode)
fmt.Fprintf(w, "http status error: %d", resp.StatusCode)
body, _ := io.ReadAll(resp.Body)
fmt.Fprintf(write, "http status error: %d\nbody: %s\n", resp.StatusCode, string(body))
go getCopilot().refresh()
return
}
if p.stream {
Expand Down Expand Up @@ -133,6 +138,9 @@ func handleProxy(w http.ResponseWriter, r *http.Request) {
req.URL.Path = strings.ReplaceAll(req.URL.Path, "/v1/", "/")

accToken, err := getCopilot().token()
if err != nil {
accToken, _ = getCopilot().refresh()
}
if accToken == "" {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "get acc token error: %v", err)
Expand Down

0 comments on commit 0f6b4e3

Please sign in to comment.