Created
May 11, 2023 22:15
-
-
Save Apurer/cf7c1a88520190a0ec7f004e442b5e0f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"net/http" | |
"os" | |
"strings" | |
) | |
type Payload struct { | |
Input string `json:"input"` | |
MaxToGenerate int `json:"max_to_generate"` | |
Temperature float64 `json:"temperature"` | |
ModelName string `json:"model_name"` | |
FileExtension string `json:"file_extension"` | |
} | |
type ResponseData struct { | |
GeneratedText string `json:"generated_text"` | |
} | |
func getAPIKey() string { | |
// Read the API key from an environment variable or a file | |
apiKey := os.Getenv("API_KEY") | |
if apiKey == "" { | |
data, err := ioutil.ReadFile("api_key.txt") | |
if err != nil { | |
panic(err) | |
} | |
apiKey = strings.TrimSpace(string(data)) | |
} | |
return apiKey | |
} | |
func apiKeyMiddleware(next http.HandlerFunc) http.HandlerFunc { | |
return func(w http.ResponseWriter, r *http.Request) { | |
apiKey := getAPIKey() | |
requestApiKey := r.Header.Get("X-API-Key") | |
if requestApiKey == "" || requestApiKey != apiKey { | |
http.Error(w, "Unauthorized", http.StatusUnauthorized) | |
return | |
} | |
next(w, r) | |
} | |
} | |
func forwardRequest(w http.ResponseWriter, r *http.Request, pythonAPIURL string) { | |
client := &http.Client{} | |
req, err := http.NewRequest("POST", pythonAPIURL, r.Body) | |
if err != nil { | |
http.Error(w, "Bad Request", http.StatusBadRequest) | |
return | |
} | |
req.Header = r.Header | |
resp, err := client.Do(req) | |
if err != nil { | |
http.Error(w, "Internal Server Error", http.StatusInternalServerError) | |
return | |
} | |
defer resp.Body.Close() | |
w.Header().Set("Content-Type", "application/json") | |
w.WriteHeader(resp.StatusCode) | |
io.Copy(w, resp.Body) | |
} | |
func handleRequest(w http.ResponseWriter, r *http.Request) { | |
pythonAPIURL := "http://localhost:5000/your-python-api-endpoint" | |
forwardRequest(w, r, pythonAPIURL) | |
} | |
func main() { | |
http.HandleFunc("/api/endpoint", apiKeyMiddleware(handleRequest)) | |
fmt.Println("Server listening on port 8080...") | |
http.ListenAndServe(":8080", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment