Skip to content

Instantly share code, notes, and snippets.

@edp1096
Last active July 21, 2024 18:44
Show Gist options
  • Save edp1096/1876a6cab7f5e0b4b7a18a01b73f5bff to your computer and use it in GitHub Desktop.
Save edp1096/1876a6cab7f5e0b4b7a18a01b73f5bff to your computer and use it in GitHub Desktop.
달러원 환율
package main
import (
"fmt"
"io"
"net/http"
"regexp"
"strings"
)
func main() {
// url := "https://www.exchange-rates.org/ko/exchange-rate-history/usd-krw-2024-07-19"
url := "https://www.google.com/search?q=USD+KRW+RATE"
resp, err := http.Get(url)
if err != nil {
fmt.Println("failed to send request:", err)
return
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Println("failed to read response:", err)
return
}
html := string(body)
// targetStr := "대한민국 원"
targetStr := " 대한민국 원"
startIndex := strings.Index(html, targetStr)
if startIndex == -1 {
fmt.Println(html)
fmt.Println("could not find the string.")
return
}
contextLength := 50
startIndex = startIndex - contextLength
if startIndex < 0 {
startIndex = 0
}
endIndex := startIndex + contextLength + len(targetStr)
if endIndex > len(html) {
endIndex = len(html)
}
rawContext := html[startIndex:endIndex]
re := regexp.MustCompile(`[0-9]+(\,[0-9]{3})*\.[0-9]+`)
match := re.FindString(rawContext)
if match == "" {
fmt.Println("could not find any number.")
return
}
exchangeRate := strings.ReplaceAll(match, ",", "")
fmt.Println("Exchange rate 1 USD to KRW:", exchangeRate)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment