Skip to content

Instantly share code, notes, and snippets.

@podhmo
Last active September 17, 2019 15:38
Show Gist options
  • Save podhmo/9d573c9b825007e6b5774f9365f61039 to your computer and use it in GitHub Desktop.
Save podhmo/9d573c9b825007e6b5774f9365f61039 to your computer and use it in GitHub Desktop.
package main
import (
"net/http"
"testing"
webtest "github.com/podhmo/go-webtest"
"github.com/podhmo/go-webtest/try"
)
func TestAPI(t *testing.T) {
c := webtest.NewClientFromHandler(http.HandlerFunc(Add))
var want interface{}
try.It{
Code: http.StatusOK,
Want: &want,
}.With(t, c, "GET", "/api/add?x=10&y=20&z=foo")
}
package main
import (
"fmt"
"log"
"net/http"
"strconv"
)
// Add
func Add(w http.ResponseWriter, req *http.Request) {
qs := req.URL.Query()
var ans int
for _, vs := range qs {
for _, v := range vs {
v, err := strconv.Atoi(v)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `{"error": %q}`, err.Error())
return
}
ans += v
}
}
fmt.Fprintf(w, `{"ans": %d}`, ans)
}
func main() {
mux := &http.ServeMux{}
mux.HandleFunc("/api/add", Add)
log.Fatal(http.ListenAndServe(":8080", mux))
}
server:
go run main.go
client:
http -b GET ":8080/api/add?x=10&y=20"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment