goffy/main.go

76 lines
1.5 KiB
Go

package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
)
type Result struct {
Exist bool `json:"exist"`
Message string `json:"message"`
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", getRoot)
mux.HandleFunc("/result", getResult)
err := http.ListenAndServe(":3333", mux)
if errors.Is(err, http.ErrServerClosed) {
fmt.Println("server closed")
} else if err != nil {
panic(err)
}
}
func getResult(w http.ResponseWriter, r *http.Request) {
// Get the url from query
url := r.URL.Query().Get("url")
if url == "" {
fmt.Println("got /result request")
io.WriteString(w, "This is result page!")
return
}
// Url to send request to
iffy_url := "https://iffy.cert.hr/validate"
// Json to send
jsonString := `{"match": "` + url + `"}`
jsonData := []byte(jsonString)
// Creating a http request, and making a http request
request, err := http.NewRequest("POST", iffy_url, bytes.NewBuffer(jsonData))
request.Header.Set("Content-type", "application/json")
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
panic(err)
}
// Read the body request
defer response.Body.Close()
body, _ := io.ReadAll(response.Body)
var result Result
// Read the json parse it
if err := json.Unmarshal(body, &result); err != nil {
panic(err)
}
fmt.Println("got /result request")
fmt.Println(result.Message)
io.WriteString(w, result.Message)
}
func getRoot(w http.ResponseWriter, r *http.Request) {
fmt.Println("got / request")
io.WriteString(w, "This is my website!")
}