如何更紧凑地编写此块?我认为编写这么简单的代码需要很多代码。
// GetSegments Retrieve segments near given coordinate.
func GetSegments(w http.ResponseWriter, r *http.Request) {
near := r.FormValue("near")
givenCoordinate := strings.Split(near, ",")
lat, _ := strconv.ParseFloat(givenCoordinate[0], 32)
lon, _ := strconv.ParseFloat(givenCoordinate[1], 32)
lat32 := float32(lat)
lon32 := float32(lon)
coord := Coordinate{
Latitude: lat32,
Longitude: lon32}
fmt.Println(coord)
}
此代码块通过Web API调用: http://localhost:8080/segments?near=14.52872,52.21244
我真的很喜欢Go,但这是我想知道我是否正确使用它的事情之一..
答案 0 :(得分:2)
最重要的是,您编写的代码可以生成有效错误消息的正确结果。检查错误。例如,
type Coordinate struct {
Latitude float32
Longitude float32
}
// GetSegments Retrieve segments near given coordinate.
// http://localhost:8080/segments?near=14.52872,52.21244
func GetSegments(w http.ResponseWriter, r *http.Request) (Coordinate, error) {
const fnc = "GetSegments"
near := r.FormValue("near")
if len(near) == 0 {
return Coordinate{}, fmt.Errorf("%s: near coordinates missing", fnc)
}
latlon := strings.Split(near, ",")
if len(latlon) != 2 {
return Coordinate{}, fmt.Errorf("%s: near coordinates error: %s", fnc, near)
}
lat, err := strconv.ParseFloat(latlon[0], 32)
if err != nil {
return Coordinate{}, fmt.Errorf("%s: near latitude: %s: %s", fnc, latlon[0], err)
}
lon, err := strconv.ParseFloat(latlon[1], 32)
if err != nil {
return Coordinate{}, fmt.Errorf("%s: near longitude: %s: %s", fnc, latlon[1], err)
}
coord := Coordinate{
Latitude: float32(lat),
Longitude: float32(lon),
}
fmt.Println(coord)
return coord, nil
}