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.
		
		
		
		
		
			
		
			
				
					
					
						
							63 lines
						
					
					
						
							1.5 KiB
						
					
					
				
			
		
		
		
			
			
			
				
					
				
				
					
				
			
		
		
	
	
							63 lines
						
					
					
						
							1.5 KiB
						
					
					
				| package fizzbuzz | |
| 
 | |
| import ( | |
| 	"encoding/json" | |
| 	"fmt" | |
| 	"log" | |
| 	"net/http" | |
| 	"net/url" | |
| 	"strconv" | |
| ) | |
| 
 | |
| // 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 = parseIntFromURL(r.URL, "int1"); err != nil { | |
| 		http.Error(w, err.Error(), http.StatusBadRequest) | |
| 		return | |
| 	} | |
| 	if in.int2, err = parseIntFromURL(r.URL, "int2"); err != nil { | |
| 		http.Error(w, err.Error(), http.StatusBadRequest) | |
| 		return | |
| 	} | |
| 	if in.limit, err = parseIntFromURL(r.URL, "limit"); err != nil { | |
| 		http.Error(w, err.Error(), http.StatusBadRequest) | |
| 		return | |
| 	} | |
| 
 | |
| 	if err = json.NewEncoder(w).Encode(in.generateFizzbuzz()); err != nil { | |
| 		log.Printf("error while encoding '%#v': %s", in, err.Error()) | |
| 		http.Error(w, "encoding problem", http.StatusInternalServerError) | |
| 	} | |
| } | |
| 
 | |
| func parseIntFromURL(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 | |
| }
 | |
| 
 |