1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
|
package router
import (
"encoding/json"
"errors"
"net/http"
"github.com/gorilla/mux"
"github.com/rootless-containers/bypass4netns/pkg/api"
)
type Backend struct {
BypassDriver BypassDriver
}
type BypassDriver interface {
ListBypass() []api.BypassStatus
StartBypass(*api.BypassSpec) (*api.BypassStatus, error)
StopBypass(id string) error
}
func (b *Backend) onError(w http.ResponseWriter, r *http.Request, err error, ec int) {
w.WriteHeader(ec)
w.Header().Set("Content-Type", "application/json")
// it is safe to return the err to the client, because the client is reliable
e := api.ErrorJSON{
Message: err.Error(),
}
_ = json.NewEncoder(w).Encode(e)
}
func (b *Backend) GetBypasses(w http.ResponseWriter, r *http.Request) {
bs := b.BypassDriver.ListBypass()
m, err := json.Marshal(bs)
if err != nil {
b.onError(w, r, err, http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(m)
}
func (b *Backend) PostBypass(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var bSpec api.BypassSpec
if err := decoder.Decode(&bSpec); err != nil {
b.onError(w, r, err, http.StatusBadRequest)
return
}
bypassStatus, err := b.BypassDriver.StartBypass(&bSpec)
if err != nil {
b.onError(w, r, err, http.StatusBadRequest)
return
}
m, err := json.Marshal(bypassStatus)
if err != nil {
b.onError(w, r, err, http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_, _ = w.Write(m)
}
func (b *Backend) DeleteBypass(w http.ResponseWriter, r *http.Request) {
id, ok := mux.Vars(r)["id"]
if !ok {
b.onError(w, r, errors.New("id not specified"), http.StatusBadRequest)
return
}
if err := b.BypassDriver.StopBypass(id); err != nil {
b.onError(w, r, err, http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
}
func AddRoutes(r *mux.Router, b *Backend) {
v1 := r.PathPrefix("/v1").Subrouter()
v1.Path("/bypass").Methods("GET").HandlerFunc(b.GetBypasses)
v1.Path("/bypass").Methods("POST").HandlerFunc(b.PostBypass)
v1.Path("/bypass/{id}").Methods("DELETE").HandlerFunc(b.DeleteBypass)
}
|