You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
65 lines
1.6 KiB
65 lines
1.6 KiB
|
8 years ago
|
package fizzbuzz
|
||
|
|
|
||
|
|
import (
|
||
|
|
"encoding/json"
|
||
|
|
"fmt"
|
||
|
|
"net/http"
|
||
|
|
"net/url"
|
||
|
|
"strconv"
|
||
|
|
|
||
|
|
"github.com/wallix/awless/logger"
|
||
|
|
)
|
||
|
|
|
||
|
|
// Server represents an instance of a fizzbuzz server
|
||
|
|
type Server struct{}
|
||
|
|
|
||
|
|
// Routes returns the routes of the fizzbuzz server
|
||
|
|
func (s *Server) Routes() http.Handler {
|
||
|
|
mux := http.NewServeMux()
|
||
|
|
mux.HandleFunc("/", s.handleFizzBuzz)
|
||
|
|
return mux
|
||
|
|
}
|
||
|
|
|
||
|
|
func (s *Server) handleFizzBuzz(w http.ResponseWriter, r *http.Request) {
|
||
|
|
if r.URL.Path != "/" {
|
||
|
|
// The "/" pattern matches everything,
|
||
|
|
// so we need to check that we're at the root here
|
||
|
|
http.NotFound(w, r)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
in := &inputs{}
|
||
|
|
|
||
|
|
in.string1 = r.URL.Query().Get("string1")
|
||
|
|
in.string2 = r.URL.Query().Get("string2")
|
||
|
|
|
||
|
|
var err error
|
||
|
|
if in.int1, err = parseInt(r.URL, "int1"); err != nil {
|
||
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
if in.int2, err = parseInt(r.URL, "int2"); err != nil {
|
||
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
if in.limit, err = parseInt(r.URL, "limit"); err != nil {
|
||
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
if err = json.NewEncoder(w).Encode(in.generateFizzbuzz()); err != nil {
|
||
|
|
logger.Errorf("error while encoding '%#v': %s", in, err.Error())
|
||
|
|
http.Error(w, "encoding problem", http.StatusInternalServerError)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func parseInt(url *url.URL, paramName string) (int, error) {
|
||
|
|
if param := url.Query().Get(paramName); param != "" {
|
||
|
|
intParam, err := strconv.Atoi(param)
|
||
|
|
if err != nil {
|
||
|
|
return 0, fmt.Errorf("%s: invalid integer '%s'", paramName, param)
|
||
|
|
}
|
||
|
|
return intParam, nil
|
||
|
|
}
|
||
|
|
return 0, nil
|
||
|
|
}
|