init
This commit is contained in:
commit
3a549b93c3
3 changed files with 92 additions and 0 deletions
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
.idea/
|
1
go.mod
Normal file
1
go.mod
Normal file
|
@ -0,0 +1 @@
|
|||
module sproxy
|
90
main.go
Normal file
90
main.go
Normal file
|
@ -0,0 +1,90 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ResponseData struct {
|
||||
body []byte
|
||||
headers map[string]string
|
||||
}
|
||||
|
||||
var cache map[string]ResponseData
|
||||
|
||||
func refresh() {
|
||||
for true {
|
||||
fmt.Println("refrech cache")
|
||||
for url, _ := range cache {
|
||||
data, err := makeHTTPRequst(url)
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
continue
|
||||
}
|
||||
cache[url] = data
|
||||
}
|
||||
time.Sleep(1 * time.Minute)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
go refresh()
|
||||
cache = make(map[string]ResponseData)
|
||||
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
|
||||
url := request.URL.Query().Get("url")
|
||||
data, ok := cache[url]
|
||||
if ok {
|
||||
returnesponseData(data, writer)
|
||||
return
|
||||
}
|
||||
|
||||
data, err := makeHTTPRequst(url)
|
||||
if err != nil {
|
||||
writer.WriteHeader(500)
|
||||
writer.Write([]byte(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
cache[url] = data
|
||||
returnesponseData(data, writer)
|
||||
})
|
||||
|
||||
err := http.ListenAndServe(":3333", nil)
|
||||
fmt.Println(err)
|
||||
}
|
||||
|
||||
func returnesponseData(responseData ResponseData, writer http.ResponseWriter) {
|
||||
for v, h := range responseData.headers {
|
||||
writer.Header().Add(v, h)
|
||||
}
|
||||
writer.WriteHeader(http.StatusOK)
|
||||
writer.Write(responseData.body)
|
||||
}
|
||||
|
||||
func makeHTTPRequst(url string) (ResponseData, error) {
|
||||
data, err := http.Get(url)
|
||||
if err != nil {
|
||||
return ResponseData{}, err
|
||||
}
|
||||
|
||||
if data.StatusCode != http.StatusOK {
|
||||
return ResponseData{}, errors.New("no http 200")
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(data.Body)
|
||||
if err != nil {
|
||||
return ResponseData{}, err
|
||||
}
|
||||
|
||||
rd := ResponseData{}
|
||||
rd.body = body
|
||||
rd.headers = make(map[string]string)
|
||||
rd.headers["content-length"] = data.Header.Get("content-length")
|
||||
rd.headers["content-type"] = data.Header.Get("content-type")
|
||||
rd.headers["x-cache"] = time.Now().Format(time.RFC3339)
|
||||
|
||||
return rd, nil
|
||||
}
|
Loading…
Reference in a new issue