Skip to content

Instantly share code, notes, and snippets.

@derekkenney
Last active July 2, 2019 20:49
Show Gist options
  • Save derekkenney/efc2d57c9263c1f7d17fb867fd2097e6 to your computer and use it in GitHub Desktop.
Save derekkenney/efc2d57c9263c1f7d17fb867fd2097e6 to your computer and use it in GitHub Desktop.

A solution to the common interview question of finding odd numbers between two ints

Implemented as a simple REST API

Example

package main
//create an http server with router
import (
"context"
"encoding/json"
"github.com/gorilla/mux"
"log"
"net/http"
"strconv"
"time"
)
func main() {
httpServer := &http.Server{
Addr: ":8080",
Handler: initRouter(),
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
}
log.Println("HTTP server is listening ...")
log.Fatal(httpServer.ListenAndServe())
}
func initRouter() *mux.Router {
router := mux.NewRouter()
router.HandleFunc("/api/oddnumbers/{l}/{r}", oddNumbers).Methods("GET")
return router
}
func oddNumbers(w http.ResponseWriter, req *http.Request) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
vars := mux.Vars(req)
l, err := strconv.Atoi(vars["l"])
r, err := strconv.Atoi(vars["r"])
errorHandler(err, ctx)
results := findOddNumbersInRange(l, r)
j, err := json.Marshal(&results)
errorHandler(err, ctx)
w.Header().Set("Content-Type", "application/json; charset=utf8")
w.Write(j)
}
func findOddNumbersInRange(l, r int) []int {
var results []int
for i := l; i <= r; i++ {
if i%2 != 0 {
results = append(results, i)
}
}
return results
}
func errorHandler(err error, ctx context.Context) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if err != nil {
log.Fatalf("Error marshaling data %v\n", err.Error())
cancel()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment