Hi Team,
I am go confused about using packages and github thing in the below code.
Please help and explain me what I am doing wrong. I have shared the project structure in the image format and the entire code - two files ( main.go and data.go) in the respective project structure files.
The code is throwing me errors at the below line : romanNumerals not found…
html.EscapeString(romanNumerals.Numerals[number]))
Please correct the code and help me understand how to do it right.
main.go
package main
import (
"fmt"
"html"
"net/http"
"strconv"
"strings"
"time"
//"github.com/sgarg2023/romanNumerals"
)
func main() {
// http package has methods for dealing with requests
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
urlPathElements := strings.Split(r.URL.Path, "/")
// If request is GET with correct syntax
if urlPathElements[1] == "roman_number" {
number, _ := strconv.Atoi(strings.TrimSpace(urlPathElements[2]))
if number == 0 || number > 10 {
// If resource is not in the list, send Not Found status
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("404 - Not Found"))
} else {
fmt.Fprintf(w, "%q",
html.EscapeString(romanNumerals.Numerals[number]))
}
} else {
// For all other requests, tell that Client sent a bad request
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("400 - Bad request"))
}
})
// Create a server and run it on 8000 port
s := &http.Server{
Addr: ":8000",
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
s.ListenAndServe()
}
data.go
package romanNumerals
var Numerals = map[int]string{
10: "X",
9: "IX",
8: "VIII",
7: "VII",
6: "VI",
5: "V",
4: "IV",
3: "III",
2: "II",
1: "I",
}